首页 \ 问答 \ 这个PHP验证码脚本有什么问题?(What is wrong with this PHP captcha script?)

这个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
更新时间:2020-02-01 04:27

最满意答案

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

相关问答

更多

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)