Home Backend Development PHP Tutorial PHP生成各种常见验证码和Ajax验证过程_php实例

PHP生成各种常见验证码和Ajax验证过程_php实例

Jun 07, 2016 pm 05:09 PM
php generates verification code image

验证码在WEB应用中非常重要,通常用来防止用户恶意提交表单,如恶意注册和登录、论坛恶意灌水等。本文将通过实例讲解使用PHP生成各种常见的验证码包括数字验证码、数字+字母验证码、中文验证码、算术验证码等等以及其Ajax验证过程。

PHP生成验证码图片

PHP生成验证码的原理:使用PHP的GD库,生成一张带验证码的图片,并将验证码保存在Session中。

PHP生成验证码的大致流程有:

1.产生一张png的图片;

2.为图片设置背景色;

3.设置字体颜色和样式;

4.产生4位数的随机的验证码;

5.把产生的每个字符调整旋转角度和位置画到png图片上;

6.加入噪点和干扰线防止注册机器分析原图片来恶意破解验证码;

7.输出图片;

8.释放图片所占内存。

示例:

session_start(); 
getCode(4,60,20); 
function getCode($num,$w,$h) { 
$code = ""; 
for ($i = 0; $i < $num; $i++) { 
$code .= rand(0, 9); 
} 
//4位验证码也可以用rand(1000,9999)直接生成 
//将生成的验证码写入session,备验证时用 
$_SESSION["helloweba_num"] = $code; 
//创建图片,定义颜色值 
header("Content-type: image/PNG"); 
$im = imagecreate($w, $h); 
$black = imagecolorallocate($im, 0, 0, 0); 
$gray = imagecolorallocate($im, 200, 200, 200); 
$bgcolor = imagecolorallocate($im, 255, 255, 255); 
//填充背景 
imagefill($im, 0, 0, $gray); 
//画边框 
imagerectangle($im, 0, 0, $w-1, $h-1, $black); 
//随机绘制两条虚线,起干扰作用 
$style = array ($black,$black,$black,$black,$black, 
$gray,$gray,$gray,$gray,$gray 
); 
imagesetstyle($im, $style); 
$y1 = rand(0, $h); 
$y2 = rand(0, $h); 
$y3 = rand(0, $h); 
$y4 = rand(0, $h); 
imageline($im, 0, $y1, $w, $y3, IMG_COLOR_STYLED); 
imageline($im, 0, $y2, $w, $y4, IMG_COLOR_STYLED); 
//在画布上随机生成大量黑点,起干扰作用; 
for ($i = 0; $i < 80; $i++) { 
imagesetpixel($im, rand(0, $w), rand(0, $h), $black); 
} 
//将数字随机显示在画布上,字符的水平间距和位置都按一定波动范围随机生成 
$strx = rand(3, 8); 
for ($i = 0; $i < $num; $i++) { 
$strpos = rand(1, 6); 
imagestring($im, 5, $strx, $strpos, substr($code, $i, 1), $black); 
$strx += rand(8, 12); 
} 
imagepng($im);//输出图片 
imagedestroy($im);//释放图片所占内存 
}
Copy after login

代码中,自定义函数getCode()诠释了验证码的生成过程。运用PHP GD库自带的图像处理函数,能轻松生成各种想要的图片效果。

imagecreate() :创建一个新图像
imagecolorallocate() :为图像分配颜色
imagefill() :填充图像
imagerectangle() :画一个矩形(边框)
imagesetstyle() :设置画线风格
imageline() :画一条线段
imagesetpixel() :画点像素
imagepng() :以PNG格式将图像输出到浏览器或文件
imagedestroy() :释放图片所占内存
将上述代码保存为code_num.php,以便调用。

Ajax刷新和验证

验证码生成后,我们要在实际的项目中应用,通常我们使用ajax可以实现点击验证码时刷新生成新的验证码(有时生成的验证码肉眼很难识别),即“看 不清换一张”。填写验证码后,还需要验证所填验证码是否正确,验证的过程是要后台程序来完成,但是我们也可以通过ajax来实现无刷新验证。

我们建立一个前端页面index.html,载入jquery,同时在body中加入验证码表单元素:

<p>验证码:<input type="text" class="input" id="code_num" name="code_num" maxlength="4" /> 
<img  src="/static/imghw/default1.png"  data-src="code_num.php"  class="lazy" id="getcode_num" title="看不清,点击换一张" align="absmiddle" alt="PHP生成各种常见验证码和Ajax验证过程_php实例" ></p> 
<p><input type="button" class="btn" id="chk_num" value="提交" /></p>
Copy after login

html代码中,PHP生成各种常见验证码和Ajax验证过程_php实例

$(function(){ 
//数字验证 
$("#getcode_num").click(function(){ 
$(this).attr("src",'code_num.php&#63;' + Math.random()); 
}); 
... 
});
Copy after login

刷新验证码,其实就是重新请求了验证码生成程序,这里要注意的是调用code_num.php时要带上随机参数防止缓存。接下来填写好验证码之后,点“提交”按钮,通过$.post(),前端向后台chk_code.php发送ajax请求。

$(function(){ 
... 
$("#chk_num").click(function(){ 
var code_num = $("#code_num").val(); 
$.post("chk_code.php&#63;act=num",{code:code_num},function(msg){ 
if(msg==1){ 
alert("验证码正确!"); 
}else{ 
alert("验证码错误!"); 
} 
}); 
}); 
});
Copy after login

后台chk_code.php验证:

session_start(); 
$code = trim($_POST['code']); 
if($code==$_SESSION["helloweba_num"]){ 
echo '1'; 
}
Copy after login

后台根据提交的验证码与保存在session中的验证码比对,完成验证。

对于其他几种验证的生成和使用,其原理一样,开发者可以根据需要,产生多种样式的随机验证码,本文演示demo中提供了数字验证码、数字+字母验证码、中文验证码、仿google验证码,算术验证码等。限于篇幅,其他几种验证码的生成代码略过,敬请谅解。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles