如何使用GD库在PHP中创建验证码

How to create captcha in PHP using GD library Today I will tell you about very important thing – captcha protection. Usually this is very important to prevent automated sign-ups in your registration forms, comment spam in blogs and guestbooks, or another brute force attacks. I will give sample how to draw protection image using our hands.

如何使用GD库在PHP中创建验证码今天,我将向您介绍非常重要的事情-验证码保护。 通常,这对于防止自动注册表格,在博客和留言簿中评论垃圾邮件或其他暴力攻击非常重要。 我将举例说明如何用我们的双手绘制保护图像。

Here are samples and downloadable package:

以下是示例和可下载的软件包:

现场演示

[sociallocker]

[社交储物柜]

打包下载

[/sociallocker]

[/ sociallocker]

Ok, download the example files and lets start coding !

好的,下载示例文件并开始编码!

步骤1. HTML (Step 1. HTML)

As usual, we start with the HTML.

和往常一样,我们从HTML开始。

This is our main page code.

这是我们的主页代码。

index.html (index.html)

<script src="js/jquery.min.js"></script>
<script src="js/md5.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="templates/css/main.css" type="text/css" />
<div class="captcha_example">
    <h3><a href="#">Captcha generation using GD, using MD5 to encrypt security text</a></h3>
    <div>
        <div style="margin-bottom:10px;">
            <h4>Security image:</h4>
            <img src="captcha.php" class="form_captcha" />
            <div class="lines">Verification (Type what you see):</div>
            <input type="text" name="captcha" value="" class="captcha" />
            <button onclick="checkCaptcha()">Check it</button>
        </div>
        <p>
            Current sample draw security image using GD library, each time when page loads it show different symbol-digit combinations. This combination processing through MD5 encription and storing in cookies. So you will able to check cookies after (where it necessary). In my sample I checking it using javascript. Try it!
        </p>
    </div>
</div>

<script src="js/jquery.min.js"></script>
<script src="js/md5.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="templates/css/main.css" type="text/css" />
<div class="captcha_example">
    <h3><a href="#">Captcha generation using GD, using MD5 to encrypt security text</a></h3>
    <div>
        <div style="margin-bottom:10px;">
            <h4>Security image:</h4>
            <img src="captcha.php" class="form_captcha" />
            <div class="lines">Verification (Type what you see):</div>
            <input type="text" name="captcha" value="" class="captcha" />
            <button onclick="checkCaptcha()">Check it</button>
        </div>
        <p>
            Current sample draw security image using GD library, each time when page loads it show different symbol-digit combinations. This combination processing through MD5 encription and storing in cookies. So you will able to check cookies after (where it necessary). In my sample I checking it using javascript. Try it!
        </p>
    </div>
</div>

To display captcha (security image) we will just draw image with php-source: captcha.php. It will generate image for us. Generated text will processed via MD5 and stored in cookies to following recognition and checking.

为了显示验证码(安全图像),我们将使用php-source:captcha.php绘制图像。 它将为我们生成图像。 生成的文本将通过MD5处理,并存储在Cookie中,以供后续识别和检查。

步骤2. CSS (Step 2. CSS)

Here are used CSS styles.

这是使用CSS样式。

模板/css/main.css (templates/css/main.css)

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.captcha_example{background:#FFF;width:865px;font-size:80%;border:1px #000 solid;margin:0.5em 10% 0.5em;padding:1em 2em 2em;-moz-border-radius: 3px;-webkit-border-radius: 3px}
.lines{margin:10px 0}

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.captcha_example{background:#FFF;width:865px;font-size:80%;border:1px #000 solid;margin:0.5em 10% 0.5em;padding:1em 2em 2em;-moz-border-radius: 3px;-webkit-border-radius: 3px}
.lines{margin:10px 0}

步骤3. JS (Step 3. JS)

Here are necessary JS files to our project.

这是我们项目的必要JS文件。

js / main.js (js/main.js)

function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}
function checkCaptcha() {
    // check captcha
    var sInsCaptcha = calcMD5($('.captcha').val());
    var sCookieCaptcha = getCookie('strSec');
    if (sInsCaptcha == sCookieCaptcha) {
        alert('Wow, great, you enter correct captcha');
    } else {
        alert('Sorry, but wrong');
    }
}

function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}
function checkCaptcha() {
    // check captcha
    var sInsCaptcha = calcMD5($('.captcha').val());
    var sCookieCaptcha = getCookie('strSec');
    if (sInsCaptcha == sCookieCaptcha) {
        alert('Wow, great, you enter correct captcha');
    } else {
        alert('Sorry, but wrong');
    }
}

We will using getCookie function to get cookies information, and checkCaptcha to validate captcha.

我们将使用getCookie函数获取Cookie信息,并使用checkCaptcha验证验证码。

js / jquery.min.js和js / md5.js (js/jquery.min.js and js/md5.js)

This is common files – jQuery library with addon for working with MD5. No need to give full code of that file here. It always available as a download package

这是常见的文件–带有用于MD5的插件的jQuery库。 无需在此处提供该文件的完整代码。 它始终可以作为下载包获得

步骤4. PHP (Step 4. PHP)

Ok, here are all used PHP file:

好的,这都是用过PHP文件:

index.php (index.php)

<?php
ob_start();
$chars = array("a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J",
               "k","K","L","m","M","n","N","o","p","P","q","Q","r","R","s","S","t","T",
               "u","U","v","V","w","W","x","X","y","Y","z","Z","2","3","4","5","6","7","8","9");
$textstr = '';
for ($i = 0, $length = 5; $i < $length; $i++)
   $textstr .= $chars[rand(0, count($chars) - 1)];
$hashtext = md5($textstr);
setcookie('strSec', $hashtext, 0, '/');
if (produceCaptchaImage($textstr) != IMAGE_ERROR_SUCCESS) {
    // output header
    header( "Content-Type: image/gif" );
    header("Expires: Mon, 21 Jul 2010 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache" );
    // output error image
    @readfile('captcha/captcha_error.gif');
}
ob_end_flush();
function produceCaptchaImage($text) {
    // constant values
    $backgroundSizeX = 2000;
    $backgroundSizeY = 350;
    $sizeX = 200;
    $sizeY = 50;
    $fontFile = "captcha/verdana.ttf";
    $textLength = strlen($text);
    // generate random security values
    $backgroundOffsetX = rand(0, $backgroundSizeX - $sizeX - 1);
    $backgroundOffsetY = rand(0, $backgroundSizeY - $sizeY - 1);
    $angle = rand(-5, 5);
    $fontColorR = rand(0, 127);
    $fontColorG = rand(0, 127);
    $fontColorB = rand(0, 127);
    $fontSize = rand(14, 24);
    $textX = rand(0, (int)($sizeX - 0.9 * $textLength * $fontSize)); // these coefficients are empiric
    $textY = rand((int)(1.25 * $fontSize), (int)($sizeY - 0.2 * $fontSize)); // don't try to learn how they were taken out
    $gdInfoArray = gd_info();
    if (! $gdInfoArray['PNG Support'])
        return IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED;
    // create image with background
    $src_im = imagecreatefrompng( "captcha/background.png");
    if (function_exists('imagecreatetruecolor')) {
        // this is more qualitative function, but it doesn't exist in old GD
        $dst_im = imagecreatetruecolor($sizeX, $sizeY);
        $resizeResult = imagecopyresampled($dst_im, $src_im, 0, 0, $backgroundOffsetX, $backgroundOffsetY, $sizeX, $sizeY, $sizeX, $sizeY);
    } else {
        // this is for old GD versions
        $dst_im = imagecreate( $sizeX, $sizeY );
        $resizeResult = imagecopyresized($dst_im, $src_im, 0, 0, $backgroundOffsetX, $backgroundOffsetY, $sizeX, $sizeY, $sizeX, $sizeY);
    }
    if (! $resizeResult)
        return IMAGE_ERROR_GD_RESIZE_ERROR;
    // write text on image
    if (! function_exists('imagettftext'))
        return IMAGE_ERROR_GD_TTF_NOT_SUPPORTED;
    $color = imagecolorallocate($dst_im, $fontColorR, $fontColorG, $fontColorB);
    imagettftext($dst_im, $fontSize, -$angle, $textX, $textY, $color, $fontFile, $text);
    // output header
    header("Content-Type: image/png");
    // output image
    imagepng($dst_im);
    // free memory
    imagedestroy($src_im);
    imagedestroy($dst_im);
    return IMAGE_ERROR_SUCCESS;
}
?>

<?php
ob_start();
$chars = array("a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J",
               "k","K","L","m","M","n","N","o","p","P","q","Q","r","R","s","S","t","T",
               "u","U","v","V","w","W","x","X","y","Y","z","Z","2","3","4","5","6","7","8","9");
$textstr = '';
for ($i = 0, $length = 5; $i < $length; $i++)
   $textstr .= $chars[rand(0, count($chars) - 1)];
$hashtext = md5($textstr);
setcookie('strSec', $hashtext, 0, '/');
if (produceCaptchaImage($textstr) != IMAGE_ERROR_SUCCESS) {
    // output header
    header( "Content-Type: image/gif" );
    header("Expires: Mon, 21 Jul 2010 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache" );
    // output error image
    @readfile('captcha/captcha_error.gif');
}
ob_end_flush();
function produceCaptchaImage($text) {
    // constant values
    $backgroundSizeX = 2000;
    $backgroundSizeY = 350;
    $sizeX = 200;
    $sizeY = 50;
    $fontFile = "captcha/verdana.ttf";
    $textLength = strlen($text);
    // generate random security values
    $backgroundOffsetX = rand(0, $backgroundSizeX - $sizeX - 1);
    $backgroundOffsetY = rand(0, $backgroundSizeY - $sizeY - 1);
    $angle = rand(-5, 5);
    $fontColorR = rand(0, 127);
    $fontColorG = rand(0, 127);
    $fontColorB = rand(0, 127);
    $fontSize = rand(14, 24);
    $textX = rand(0, (int)($sizeX - 0.9 * $textLength * $fontSize)); // these coefficients are empiric
    $textY = rand((int)(1.25 * $fontSize), (int)($sizeY - 0.2 * $fontSize)); // don't try to learn how they were taken out
    $gdInfoArray = gd_info();
    if (! $gdInfoArray['PNG Support'])
        return IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED;
    // create image with background
    $src_im = imagecreatefrompng( "captcha/background.png");
    if (function_exists('imagecreatetruecolor')) {
        // this is more qualitative function, but it doesn't exist in old GD
        $dst_im = imagecreatetruecolor($sizeX, $sizeY);
        $resizeResult = imagecopyresampled($dst_im, $src_im, 0, 0, $backgroundOffsetX, $backgroundOffsetY, $sizeX, $sizeY, $sizeX, $sizeY);
    } else {
        // this is for old GD versions
        $dst_im = imagecreate( $sizeX, $sizeY );
        $resizeResult = imagecopyresized($dst_im, $src_im, 0, 0, $backgroundOffsetX, $backgroundOffsetY, $sizeX, $sizeY, $sizeX, $sizeY);
    }
    if (! $resizeResult)
        return IMAGE_ERROR_GD_RESIZE_ERROR;
    // write text on image
    if (! function_exists('imagettftext'))
        return IMAGE_ERROR_GD_TTF_NOT_SUPPORTED;
    $color = imagecolorallocate($dst_im, $fontColorR, $fontColorG, $fontColorB);
    imagettftext($dst_im, $fontSize, -$angle, $textX, $textY, $color, $fontFile, $text);
    // output header
    header("Content-Type: image/png");
    // output image
    imagepng($dst_im);
    // free memory
    imagedestroy($src_im);
    imagedestroy($dst_im);
    return IMAGE_ERROR_SUCCESS;
}
?>

Here are several comments by code:

以下是一些代码注释:

In start we will define array of used characters – $chars. After, we will compose string (5 letters) with random characters. After, will MD5 this result string and save it into cookies. We will use this to more security. So any bot or special script will unable to find this key even after detail investigation of result page.

首先,我们将定义使用字符数组– $ chars。 之后,我们将用随机字符组成字符串(5个字母)。 之后,将MD5这个结果字符串并保存到cookie中。 我们将使用它来提高安全性。 因此,即使在对结果页进行详细调查后,任何漫游器或特殊脚本也无法找到该密钥。

produceCaptchaImage is main function which will draw our captcha. It take just 1 param – text which we going to draw. We will using GD library to draw. We will randomly choose position to text in captcha, angle (+- 5 degrees), font color. After will get our background image which will mage reading of our code more difficult, and, will draw result text on this image.

ProduceCaptchaImage是主要功能,将绘制我们的验证码。 仅需1个参数-我们将要绘制的文本。 我们将使用GD库进行绘制。 我们将随机选择验证码,角度(+/- 5度),字体颜色的文本位置。 之后将得到我们的背景图像,这将使我们的代码阅读更加困难,并将在该图像上绘制结果文本。

现场演示

结论 (Conclusion)

Today I told you how to create our own captcha – security image. I sure that you will use it in your projects. Quite any serious project using it to protect spamming. Good luck!

今天,我告诉您如何创建自己的验证码-安全映像。 我确定您将在项目中使用它。 任何使用它来保护垃圾邮件的严肃项目。 祝好运!

翻译自: https://www.script-tutorials.com/how-to-create-captcha-in-php-using-gd-library/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值