cron - 用于验证码的 imagemagick

标签 cron imagemagick captcha

我有一个 cronjob 可以为我的在线表单(注册、联系方式和新闻通讯)生成验证码。

我每天生成超过 5000 张图像,因此当我显示表单时,我随机选择一张图像,然后简单地显示图像并设置 session 。

我的表格非常简单:

验证码(idmediumint(5)无符号PK,短语varchar(10));

然后我运行生成图像并插入数据库的 cronjob。这个过程需要一段时间才能运行,我想知道是否有更好的方法来做到这一点,以最大限度地提高性能和生成,因为我有其他全天运行的 cronjob,并且我想确保我可以将其从 cronjob 中删除这样我的定时任务就可以喘口气了。

最佳答案

创建一个名为 Captcha.class.php 的文件并放入以下内容:

class Captcha {
    private $font = '/path/to/font/yourfont.ttf'; // get any font you like and dont forget to update this.

    private function generateCode($characters) {
        $possible = '23456789bcdfghjkmnpqrstvwxyz'; // why not 1 and i, because they look similar and its hard to read sometimes
        $code = '';
        $i = 0;
        while ($i < $characters) {
            $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
            $i++;
        }
        return $code;
    }

    function getImage($width, $height, $characters) {
        $code = $this->generateCode($characters);
        $fontSize = $height * 0.75;
        $image = imagecreate($width, $height);
        if(!$image) {
            return FALSE;
        }
        $background_color = imagecolorallocate($image, 255, 255, 255);
        $text_color = imagecolorallocate($image, 66, 42, 32);
        $noiseColor = imagecolorallocate($image, 150, 150, 150);
        for( $i=0; $i<($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noiseColor);
        }
        for( $i=0; $i<($width*$height)/150; $i++ ) {
            imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noiseColor);
        }
        $textbox = imagettfbbox($fontSize, 0, $this->font, $code);
        if(!$textbox) {
            return FALSE;
        }
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $fontSize, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        $_SESSION['captcha'] = $code;
    }
}

然后在您的页面中您可以执行以下操作:

<img src="/captcha.php" />

然后在 /captcha.php 中输入:

session_start();
require('Captcha.class.php');
$Captcha = new Captcha();
$Captcha->getImage(120,40,6);

您也可以更改参数,因为您也希望显示不同的验证码。

这样您就可以即时生成。如果您愿意,您也可以随时将图像保存在磁盘上。

关于cron - 用于验证码的 imagemagick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9237250/

相关文章:

php - 每分钟 Cronjob

opencv - 手动校正 OpenCV 中的桶形失真,没有棋盘图像

ruby-on-rails-3 - rmagick gem install "Can' t 找到 Magick-config”

python - 将多页 PDF 转换为 TIFF 不适用于 Python 库 Wand

php - 一段时间后nginx拒绝连接

Java Quartz CronExpression 验证错误的 cron 表达式

cron - 在 ubuntu 中保存 cron 作业

ruby-on-rails - 在我的 rails 3 应用程序中,simple_captcha 在生产模式下不显示图像

captcha - 简单的验证码求解

asp.net - 无需验证码即可防范 DoS 攻击