Home php教程 php手册 PHP验证码之Ajax验证实现方法

PHP验证码之Ajax验证实现方法

Jun 13, 2016 am 10:12 AM
ajax php for experience use exist accomplish us supply method user website development verify

在网站开发中为了提供用户体验我们多数都使用ajax来做一些操作,下面我来介绍一个利用ajax实现无刷新页面的验证码ajax验证有需要的朋友可参考。

验证码生成程序我这里就不介绍了,大家可参考http://www.bKjia.c0m/phper/phpanqn/46698.htm 下面介绍一个简单的

 代码如下 复制代码

session_start();
//设置: 你可以在这里修改验证码图片的参数
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = './monofont.ttf'; 
 
//以下字符将用于验证码中的字符 
//为了避免混淆去掉了数字1和字母i
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 10;
$random_lines = 30;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864"; 
 
$code = ''; 
 
$i = 0;
while ($i     $code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
    $i++;
}
 
$font_size = $image_height * 0.75; 
$image = @imagecreate($image_width, $image_height);
 
/* 设置背景、文本和干扰的噪点 */
$background_color = imagecolorallocate($image, 255, 255, 255);
 
$arr_text_color = hexrgb($captcha_text_color); 
$text_color = imagecolorallocate($image, $arr_text_color['red'], 
$arr_text_color['green'], $arr_text_color['blue']);
 
$arr_noice_color = hexrgb($captcha_noice_color); 
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'], 
$arr_noice_color['green'], $arr_noice_color['blue']);
 
/* 在背景上随机的生成干扰噪点 */
for( $i=0; $i     imagefilledellipse($image, mt_rand(0,$image_width),
    mt_rand(0,$image_height), 2, 3, $image_noise_color);
}
 
/* 在背景图片上,随机生成线条 */
for( $i=0; $i     imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
    mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}
 
/* 生成一个文本框,然后在里面写生6个字符 */
$textbox = imagettfbbox($font_size, 0, $font, $code); 
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);
 
/* 将验证码图片在HTML页面上显示出来 */
header('Content-Type: image/jpeg');
// 设定图片输出的类型
imagejpeg($image);
//显示图片
imagedestroy($image);
//销毁图片实例
$_SESSION['6_letters_code'] = $code;
 
function hexrgb ($hexstr) {
    $int = hexdec($hexstr);
 
    return array( "red" => 0xFF & ($int >> 0x10),
                "green" => 0xFF & ($int >> 0x8),
                "blue" => 0xFF & $int
    );
}
?>

验证码

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

验证验证码正确或错误的方法
验证码图片上的文字被存放到了SESSION 变量里面,验证的时候,我们需要将SESSION 里面的值和用户输入的值进行比较即可。

$_SESSION[6_letters_code] – 存放着验证码的文字值
$_POST[6_letters_code] – 这是用户输入的验证码的内容


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

 代码如下 复制代码

验证码:  
PHP验证码之Ajax验证实现方法

 

 

html代码中,PHP验证码之Ajax验证实现方法

 代码如下 复制代码

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

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

 代码如下 复制代码

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


后台chk_code.php验证:

 代码如下 复制代码

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

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

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 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
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

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.

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.

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 and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

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.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles