驗證碼產生與應用執行個體

來源:互聯網
上載者:User

驗證碼產生與應用執行個體
在寫使用者驗證頁面,如註冊,登入的時候,為了加強使用者登入的安全性,添加驗證碼驗證。
驗證碼通過gd產生png圖片,並把$randval隨機數字賦給$_session['login_check_num'],在通過使用者輸入的$_post進行比較,來判斷是否正確。達到需要實現的功能,需要修改php教程.ini檔案,使php支援gd庫。

<?php
//調用此頁面,如果下面的式子成立,則產生驗證碼圖片
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)<10000);{
        $_session["login_check_num"] = $randval;
        //將四位整數驗證碼繪入圖片 
        imagestring($im, 5, 10, 3, $randval, $black);
    }
    //加入幹擾象素   
    for($i=0;$i<200;$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("驗證碼輸入錯誤");
    }
}
?>

 

驗證碼,是一種區分使用者是電腦和人的公用全Bot。在captcha測試中,作為伺服器的電腦會自動產生一個問題由使用者來解答。這個問題可以由電腦產生並評判,但是必須只有人類才能解答。由於電腦無法解答captcha的問題,所以回答出問題的使用者就可以被認為是人類。

*/
session_start();
$string = null;
$im = imagecreatetruecolor(60,25);  //建立真彩圖60*25
$bg = imagecolorallocate($im,255,255,255);//白色背景
imagefill($im,0,0,$bg);填充白色
$x = 5;//
$y = 0;//文字座標
for($i=0 ; $i&lt;4 ;$i++)
{
$char = mt_rand(0,9);
$string .=$char;
$y = mt_rand(0,10);
$ccolor = imagecolorallocate($im,mt_rand(0,230),mt_rand(0,230),mt_rand(0,230));
imagechar($im,6,$x,$y,$char,$ccolor);//填充文字
$x += mt_rand(10,15);
}
for($i=0 ;$i
{
$x1 = mt_rand(0,80);
$x2 = mt_rand(0,80);
$y1 = mt_rand(0,30);
$y2 = mt_rand(0,30);
$x2 = $x1 +mt_rand(1,5);
$y2 = $y1 +mt_rand(1,5);
$lc = imagecolorallocate($im,mt_rand(0,230),mt_rand(0,230),mt_rand(0,230));
imageline($im,$x1,$y1,$x2,$y2,$lc);//填充線條
}
$_session['code'] = md5($string);
header("content-type:image/jpeg");
imagepng($im);
imagedestroy($im);

更多詳細內容請查看:http://www.111cn.net/phper/php-cy/33707.htm


當然我們也可以能過同時我們可以明知php ajax來執行個體驗證功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.