这个PHP验证码脚本有什么问题?(What is wrong with this PHP captcha script?)
我已经使用这个脚本很长一段时间了,它完美地工作在99%。 这对用户来说简单明了,我想继续使用它。
但是,偶尔稀疏用户告诉我系统在数字正确时不接受他的验证码(错误的代码)。 每次我都经过他们的cookie设置,清除缓存等,但在这些情况下似乎没有任何作用。
我的问题是,这个脚本的代码中是否有任何理由可以解释特殊情况下的故障?
session_start(); $randomnr = rand(1000, 9999); $_SESSION['randomnr2'] = md5($randomnr); $im = imagecreatetruecolor(100, 28); $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0,0,0); imagefilledrectangle($im, 0, 0, 200, 35, $black); $font = '/img/captcha/font.ttf'; imagettftext($im, 30, 0, 10, 40, $grey, $font, $randomnr); imagettftext($im, 20, 3, 18, 25, $white, $font, $randomnr); // Prevent caching header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past3 header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header ("Content-type: image/gif"); imagegif($im); imagedestroy($im);
在我的表单中,我然后将此脚本称为验证码图像的来源。 发送表单后,以这种方式检查验证码:
if(md5($_POST['norobot']) != $_SESSION['randomnr2']) { echo 'Wrong captcha!'; }
请注意
session_start();
在表单页面和表单结果页面上调用。如果有人能够在此脚本中查明潜在的错误原因,我将不胜感激!
PS:我知道验证码脚本的缺点。 我知道某些机器人仍然可以读出它们。 我不想使用Recaptcha,因为它对我的用户来说太难了(不同的语言+很多次老用户)。 我也知道md5很容易解密。
编辑编辑编辑编辑编辑编辑编辑编辑编辑编辑编辑编辑编辑编辑
在UgoMéda的评论之后,我一直在做一些实验。 这就是我创建的(为方便起见而简化):
表格
// Insert a random number of four digits into database, along with current time $query = 'INSERT INTO captcha (number, created_date, posted) VALUES ("'.rand(1000, 9999).'", NOW(),0)'; $result = mysql_query($query); // Retrieve the id of the inserted number $captcha_uid = mysql_insert_id(); $output .= '<label for="norobot"> Enter spam protection code'; // Send id to captcha script $output .= '<img src="/img/captcha/captcha.php?number='.$captcha_uid.'" />'; // Hidden field with id $output .= '<input type="hidden" name="captcha_uid" value="'.$captcha_uid.'" />'; $output .= '<input type="text" name="norobot" class="norobot" id="norobot" maxlength="4" required />'; $output .= '</label>'; echo $output;
验证码脚本
$font = '/img/captcha/font.ttf'; connect(); // Find the number associated to the captcha id $query = 'SELECT number FROM captcha WHERE uid = "'.mysql_real_escape_string($_GET['number']).'" LIMIT 1'; $result = mysql_query($query) or trigger_error(__FUNCTION__.'<hr />'.mysql_error().'<hr />'.$query); if (mysql_num_rows($result) != 0){ while($row = mysql_fetch_assoc($result)){ $number = $row['number']; } } disconnect(); $im = imagecreatetruecolor(100, 28); $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0,0,0); imagefilledrectangle($im, 0, 0, 200, 35, $black); imagettftext($im, 30, 0, 10, 40, $grey, $font, $number); imagettftext($im, 20, 3, 18, 25, $white, $font, $number); // Generate the image from the number retrieved out of database header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past3 header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header ("Content-type: image/gif"); imagegif($im); imagedestroy($im);
表格的结果
function get_captcha_number($captcha_uid) { $query = 'SELECT number FROM captcha WHERE uid = "'.mysql_real_escape_string($captcha_uid).'" LIMIT 1'; $result = mysql_query($query); if (mysql_num_rows($result) != 0){ while($row = mysql_fetch_assoc($result)){ return $row['number']; } } // Here I would later also enter the DELETE QUERY mentioned above... } if($_POST['norobot'] != get_captcha_number($_POST['captcha_uid'])) { echo 'Captcha error' exit; }
这非常有效,所以非常感谢这个解决方案。
但是,我看到了一些潜在的缺点。 我注意到至少有4个查询,并且对我们正在做的事情感到有点资源密集。 此外,当用户多次重新加载同一页面时(只是为了混蛋),数据库会很快填满。 当然,这将在下一个表单提交时删除,但是,你能不能和我一起讨论这个可能的替代方案?
我知道通常不应该加密/解密。 但是,由于验证码本质上是有缺陷的(因为机器人的图像读数),我们难道不能通过加密和解密发送到
captcha.php
脚本的参数来简化过程吗?如果我们这样做了(遵循Alix Axel的加密/解密说明 ):
1)加密一个随机的四位数字符,如下所示:
$key = 'encryption-password-only-present-within-the-application'; $string = rand(1000,9999); $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
2)将带有参数的加密号码发送到图像脚本并将其存储在隐藏字段中
<img src="/img/captcha.php?number="'.$encrypted.'" /> <input type="hidden" name="encrypted_number" value="'.$encrypted.'" />
3)解密验证码脚本中的数字(通过$ _GET发送)并从中生成图像
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
4)再次解密表单上的数字以与用户输入进行比较$ decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256,md5($ key),base64_decode($ encrypted),MCRYPT_MODE_CBC,md5(md5($ key))),“\ 0 “);
if($ _ POST ['norobot']!= $ decrypted){echo'Capscha error!'; 出口; }同意,这有点“通过默默无闻”,但它似乎提供了一些基本的安全性,并且仍然相当简单。 或者这种加密/解密操作本身是否过于耗费资源?
有没有人对此有任何评论?
I've been using this script for a long time and it works perfectly in 99%. It's easy and clear to users and I would like to continue using it.
However, once in a while a sparse user tells me that the system doesn't accept his captcha (wrong code) while the numbers are correct. Each time I've been going over their cookies settings, clearing cache etc, but in these cases nothing seems to work.
My question thus is, is there any reason in the code of this script that would explain malfunctioning in exceptional cases?
session_start(); $randomnr = rand(1000, 9999); $_SESSION['randomnr2'] = md5($randomnr); $im = imagecreatetruecolor(100, 28); $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0,0,0); imagefilledrectangle($im, 0, 0, 200, 35, $black); $font = '/img/captcha/font.ttf'; imagettftext($im, 30, 0, 10, 40, $grey, $font, $randomnr); imagettftext($im, 20, 3, 18, 25, $white, $font, $randomnr); // Prevent caching header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past3 header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header ("Content-type: image/gif"); imagegif($im); imagedestroy($im);
In my form, I then call this script as the source of the captcha image. After sending the form, the captcha is checked this way:
if(md5($_POST['norobot']) != $_SESSION['randomnr2']) { echo 'Wrong captcha!'; }
Please note that
session_start();
is called on the form page and the form result page.If anyone could pinpoint potential error causes in this script, I would appreciate it!
P.S.: I am aware of the drawbacks of captcha scripts. I am aware that certain bots could still read them out. I do not wish to use Recaptcha, because it is too difficult for my users (different language + lots of times older users). I also am aware of the fact that md5 is easily decryptable.
EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT
Following the remarks of Ugo Méda, I've been doing some experiments. This is what I've created (simplified for your convenience):
The form
// Insert a random number of four digits into database, along with current time $query = 'INSERT INTO captcha (number, created_date, posted) VALUES ("'.rand(1000, 9999).'", NOW(),0)'; $result = mysql_query($query); // Retrieve the id of the inserted number $captcha_uid = mysql_insert_id(); $output .= '<label for="norobot"> Enter spam protection code'; // Send id to captcha script $output .= '<img src="/img/captcha/captcha.php?number='.$captcha_uid.'" />'; // Hidden field with id $output .= '<input type="hidden" name="captcha_uid" value="'.$captcha_uid.'" />'; $output .= '<input type="text" name="norobot" class="norobot" id="norobot" maxlength="4" required />'; $output .= '</label>'; echo $output;
The captcha script
$font = '/img/captcha/font.ttf'; connect(); // Find the number associated to the captcha id $query = 'SELECT number FROM captcha WHERE uid = "'.mysql_real_escape_string($_GET['number']).'" LIMIT 1'; $result = mysql_query($query) or trigger_error(__FUNCTION__.'<hr />'.mysql_error().'<hr />'.$query); if (mysql_num_rows($result) != 0){ while($row = mysql_fetch_assoc($result)){ $number = $row['number']; } } disconnect(); $im = imagecreatetruecolor(100, 28); $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0,0,0); imagefilledrectangle($im, 0, 0, 200, 35, $black); imagettftext($im, 30, 0, 10, 40, $grey, $font, $number); imagettftext($im, 20, 3, 18, 25, $white, $font, $number); // Generate the image from the number retrieved out of database header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past3 header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header ("Content-type: image/gif"); imagegif($im); imagedestroy($im);
The result of the form
function get_captcha_number($captcha_uid) { $query = 'SELECT number FROM captcha WHERE uid = "'.mysql_real_escape_string($captcha_uid).'" LIMIT 1'; $result = mysql_query($query); if (mysql_num_rows($result) != 0){ while($row = mysql_fetch_assoc($result)){ return $row['number']; } } // Here I would later also enter the DELETE QUERY mentioned above... } if($_POST['norobot'] != get_captcha_number($_POST['captcha_uid'])) { echo 'Captcha error' exit; }
This works very well, so thanks very much for this solution.
However, I'm seeing some potential drawbacks here. I'm noting at least 4 queries and feels somewhat resource intensive for what we're doing. Also, when a user would reload the same page several times (just to be an asshole), the database would quickly fill up. Of course this would all be deleted upon the next form submit, but nonetheless, could you go over this possible alternative with me?
I'm aware that one should generally not encrypt / decrypt. However, since captchas are flawed by nature (because of image readouts of bots), couldn't we simplify the process by encrypting and decrypting a parameter that is being sent to the
captcha.php
script?What if we did this (following the encrypt/decrypt instructions of Alix Axel):
1) Encrypt a random four digit character like so:
$key = 'encryption-password-only-present-within-the-application'; $string = rand(1000,9999); $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
2) Send the encrypted number with a parameter to the image script and store it in a hidden field
<img src="/img/captcha.php?number="'.$encrypted.'" /> <input type="hidden" name="encrypted_number" value="'.$encrypted.'" />
3) Decrypt the number (that was sent via $_GET) inside the captcha script and generate an image from it
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
4) Decrypt the number on form submit again to compare to user input $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
if($_POST['norobot'] != $decrypted) { echo 'Captcha error!'; exit; }Agreed, this is a little bit "security-through-obscurity", but it seems to provide some basic security and remains fairly simple. Or would this encrypt/decrypt action be too resource intensive on its own?
Does anyone have any remarks on this?
原文:https://stackoverflow.com/questions/11341666
最满意答案
ArrayAdapter的方法是
remove(int index)
:list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, final int position, long arg3) { AlertDialog.Builder alert = new AlertDialog.Builder(DeleteItem.this); alert.setMessage("Are you sure you want to delete this?"); alert.setCancelable(false); alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ArrayAdapter yourArrayAdapter = (ArrayAdapter) arg0.getAdapter(); yourArrayAdapter.remove(position); yourArrayAdapter.notifyDataSetChanged(); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); return false; } });
使用适配器的通用类型调整演员表。 仅当您向适配器提供元素集合时,它才有效。 如果你提供了一个数组,它将抛出异常
ArrayAdapter has the method
remove(int index)
:list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, final int position, long arg3) { AlertDialog.Builder alert = new AlertDialog.Builder(DeleteItem.this); alert.setMessage("Are you sure you want to delete this?"); alert.setCancelable(false); alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ArrayAdapter yourArrayAdapter = (ArrayAdapter) arg0.getAdapter(); yourArrayAdapter.remove(position); yourArrayAdapter.notifyDataSetChanged(); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); return false; } });
Adjust the cast with the generic type of your adapter. It works only if you provide a Collection of elements to the adapter. If you provided an Array it will throw an exception
相关问答
更多-
问题是您在setChoiceMode()调用setChoiceMode()和setMultiChoiceModeListener() ,这意味着在您对列表项执行长按之前,不会调用这些方法。 在您的OnItemLongClickListener之外放置editListView.setChoiceMode()和editListView.setMultiChoiceModeListener() : editListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_M ...
-
OnItemLongClicklistner上的ListView - 检索信息(ListView on OnItemLongClicklistener - retrieving information)[2024-02-03]
好吧,我有它的工作。 这是我改变的: OnItemLongClickListener listener = new OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView> arg0, View arg1, int position, long id){ Toast.makeText(getApplicationCon ... -
我认为你应该在你的onItemLongClick方法中返回true以消耗点击。 查看Android文档http://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html I think you should return true in your onItemLongClick method to consume the click. Check Android documentatio ...
-
由listview OnItemLongClickListener创建的Android开放式微调器(Android open spinner by listview OnItemLongClickListener)[2023-08-30]
我认为最好使用弹出菜单或对话框进行弹出选择,而不是在运行时制作微调器。 对于对话框,它看起来像这样: listView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView> arg0, View arg1, int arg2, long arg3) { Alert ... -
我发现了问题,我忘了从用于构建ListView的ArrayList中删除该项: codeList.remove(position); I found the problem, I forgot to remove the item from the ArrayList which I use to build the ListView: codeList.remove(position);
-
在我的方式中,我从FavoriteFragment中删除了两个方法的定义,并在MainActivity中定义了它: Json Array listView = (ListView) findViewById(R.id.list); adapterAirlines = new AirlinesAdapter(this, airlinesList); listView.setAdapter(adapterAirlines); ...
-
ArrayAdapter的方法是remove(int index) : list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(final AdapterView> arg0, View arg1, final int position, long arg3) { ...
-
好的,所以我对DynamicListView.java进行了三次重大更改 1)我在下面将setter更改为setOnItemClickListener public void init(Context context) { setOnItemClickListener(mOnItemClickListener); //setOnScrollListener(mScrollListener); DisplayMetrics metrics = context.getResour ...
-
从数据库中删除并刷新列表视图。 Delete from Database and refresh the listview.
-
在{recyclerView, position, v -> true} , recyclerView, position, v是onItemLongClick回调的参数。 你会像这样使用它: ItemClickSupport.addTo(recyclerView3).setOnItemLongClickListener { recyclerView, view, position, id -> // Use position here true // False if not consu ...