注意:以下代碼需要打開php的gd庫,修改php.in文件的配置,把已經注釋掉的行之前的分號取消即可:extension=php_gd2.dll.
實例一,代碼如下:
- $width = 165;
- $height = 120;
- $image = imagecreatetruecolor($width,$height);
- $bg_color = imagecolorallocate($image,255,255,255);
- $tm = imagecolorallocate($image,255,0,0);
- imagefilledrectangle($image,0,0,$width,$height,$bg_color);
- imagefill($image,0,0,$bg_color);
- /*
- //$text = random_text(5);
- $text = "ffff";
- $font = 8;
- $struft=iconv("gbk","utf-8",$text);
- $x = imagesx($image);
- $y = imagesy($image);
- $fg_color = imagecolorallocate($image,233,14,91);
- imagestring($image,$font,$x,$y,$struft,$fg_color);
- $_session['captcha'] = $text;
- */
- header("content-type:image/png");
- imagepng($image);
- imagedestroy($image);
實例二,代碼如下:validate.php
采用了session識別,稍微改進了一下目前網絡上流傳的php驗證碼,加入雜點,數字顏色隨機顯示,控制4位數字顯示.
- <?php
- session_start();
- //生成驗證碼圖片
- header("content-type: image/png");
- $im = imagecreate(44,18);
- $back = imagecolorallocate($im, 245,245,245);
- imagefill($im,0,0,$back); //背景
- srand((double)microtime()*1000000);
- //生成4位數字
- for($i=0;$i<4;$i++){
- $font = imagecolorallocate($im, rand(100,255),rand(0,100),rand(100,255));
- $authnum=rand(1,9);
- $vcodes.=$authnum;
- imagestring($im, 5, 2+$i*10, 1, $authnum, $font);
- }
- for($i=0;$i<100;$i++) //加入干擾象素
- { //開源代碼Vevb.com
- $randcolor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
- imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
- }
- imagepng($im);
- imagedestroy($im);
- $_session['vcode'] = $vcodes;
- ?>
下面看完整實例,代碼如下:
- <?php
- @header("content-type:text/html; charset=utf-8");
- //打開session
- session_start();
- ?>
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8" />
- <title>php驗證碼示例</title>
- </head>
- <body>
- 驗證碼:<br/>
- <iframe id="iimg" height="100" width=300 src="img.php" frameborder="0" ></iframe>
- <br/>
- <input type=button value="看不清,換一張" onclick="iimg.location.reload();">
- <br>
- <form action="validate.php" method="post">
- 輸入驗證碼:<input name="imgid" style="width:60">
- <input type="submit" value="確定">
- </form>
- </body>
- </html>
php判斷用戶輸入的驗證碼是否與系統生成的一致,代碼如下:
- <?php @header("content-type:text/html; charset=utf-8");
- //開啟session
- session_start();
- //得到用戶輸入的驗證碼,并轉換成大寫
- $imgid_req = $_request['imgid'];
- $imgid_req = strtoupper($imgid_req);
- //驗證該字符串是否注冊了session變量
- if (session_is_registered($imgid_req)) {
- echo "<font color=blue >通過驗證!</font>";
- } else {
- echo "<font color=red >驗證錯誤!</font>";
- }
- //關閉session,以清除所有注冊過的變量
- session_destroy();
- ?>
新聞熱點
疑難解答