標籤:
驗證碼產生並儲存到session
<?php//開始sessionsession_start();//畫布大小$image = imagecreate(100, 40);$color = imagecolorallocate($image, 255, 255, 255);// imagefill($image,0, 0, $color);//建立驗證碼$code = ‘‘;for($i=0;$i<4;$i++){$fontsize = 9;$fontcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));$x = $i * 25 + 10;$y = rand(5,10);$num = (string)rand(0,9);$code .= $num;imagestring($image, $fontsize, $x, $y, $num, $fontcolor);}//驗證碼記錄到session$_SESSION[‘code‘] = $code;//增加幹擾元素點for ($i=0; $i <800 ; $i++) { $color = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));imagesetpixel($image, rand(0,100), rand(0,40), $color);}//增加幹擾線for ($i=0; $i <5 ; $i++) { $color = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));imageline($image, rand(10,180), rand(10,180), rand(10,180), rand(10,180), $color);}//說明這個是一個圖片header("content-type:image/png");//輸出到瀏覽器imagepng($image);//關閉imagedestroy($image);
html檔案
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title></head><body><div><img src="yzimg.php" width="100" height="40" id="yzimg" onclick="huan()"></div><div><input type="text" id="yzm"></input></div><button id="btn">提交</button><script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script><script type="text/javascript">function huan(){var num = Math.random() * 10;document.getElementById(‘yzimg‘).src = ‘yzimg.php?r=‘ + num;}$(‘#btn‘).click(function(){$.post(‘/yzm/yz.php‘,{‘yzm‘:$(‘#yzm‘).val()},function(data){if (data == 0) {alert(‘YES‘);} else {alert(‘NO‘);huan();}})})</script></body></html>
驗證驗證碼檔案
<?php //必須開啟sessionsession_start();if ($_POST[‘yzm‘] != $_SESSION[‘code‘]) {# code...echo 1;} else {echo 0;} ?>
PHP之路——驗證碼實現