Home > php教程 > php手册 > body text

php验证码代码实例

WBOY
Release: 2016-06-13 10:37:38
Original
1003 people have browsed it

我们在写用户验证页面,如注册,登录的时候,为了加强用户登录的安全性,添加验证码验证。
验证码通过GD生成PNG图片,并把$randval随机数字赋给$_SESSION[login_check_num],在通过用户输入的$_POST进行比较,来判断是否正确。达到需要实现的功能,需要修改php.ini文件,使php支持GD库。
//调用此页面,如果下面的式子成立,则生成验证码图片
if($_GET["action"]=="verifycode")
{
    rand_create();
}
//验证码图片生成
function rand_create()
{
    //通知浏览器将要输出PNG图片
    Header("Content-type: image/PNG");
    //准备好随机数发生器种子 
    srand((double)microtime()*1000000);
    //准备图片的相关参数  
    $im = imagecreate(62,20);
    $black = ImageColorAllocate($im, 0,0,0);  //RGB黑色标识符
    $white = ImageColorAllocate($im, 255,255,255); //RGB白色标识符
    $gray = ImageColorAllocate($im, 200,200,200); //RGB灰色标识符
    //开始作图    
    imagefill($im,0,0,$gray);
    while(($randval=rand()%100000)         $_SESSION["login_check_num"] = $randval;
        //将四位整数验证码绘入图片 
        imagestring($im, 5, 10, 3, $randval, $black);
    }
    //加入干扰象素   
    for($i=0;$i         $randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255));
        imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
    }
    //输出验证图片
    ImagePNG($im);
    //销毁图像标识符
    ImageDestroy($im);
}
//检验验证码
function rand_check()
{
    if($_POST["reg_rand"] == $_SESSION["login_check_num"]){
        return true;
    }
    else{
        exit("验证码输入错误");
    }
}
?> 
 

source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!