php入門級的PHP驗證碼程式

來源:互聯網
上載者:User

執行個體

 代碼如下 複製代碼

<?php 
session_start(); 
 
$im = imagecreate(80,30);//建立圖片 
$color = imagecolorallocate($im,rand(150,200),rand(150,200),rand(150,200));//設定圖片背景 
$str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";//產生隨機字串 
 for($i=0;$i<5;$i++){ 
        $code .= $str[rand(0,(strlen($str)-1))]; 
        } 
$_SESSION['code'] = $code; 
for($a=0;$a<5;$a++){  //將字串寫入圖片資源 
    $x = $a*10 + 15; 
    $y = rand(5,10);  // www.111cn.net
    imagechar($im,5,$x,$y,$code{$a},imagecolorallocate($im,0,0,0)); 
    } 
header("Content-type:image/png");//輸出圖片資源 
imagepng($im); 
?>

例2

 代碼如下 複製代碼

<?php
if(!isset($_SESSION)){ //判斷session是否開啟
session_start(); //開啟就session
}
$width=70; //布畫寬度
$height=25; //布畫高度
$length=4;//驗證碼長度
$code=getcode($length); //擷取隨機字串
$_SESSION['verfyCode'] = $code;

$img=imagecreate($width,$height);
$bgcolor=imagecolorallocate($img,240,240,240);
$rectangelcolor=imagecolorallocate($img,150,150,150);
imagerectangle($img,1,1,$width-1,$height-1,$rectangelcolor);//畫邊框
for($i=0;$i<$length;$i++){//迴圈寫字
$codecolor=imagecolorallocate($img,mt_rand(50,200),mt_rand(50,128),mt_rand(50,200));
$angle=rand(-20,20);
$charx=$i*15+8;
$chary=($height+14)/2+rand(-1,1);
imagettftext($img,15,$angle,$charx,$chary,$codecolor,'C:WINDOWSFontsSIMKAI.TTF',
$code[$i]);
}
for($i=0;$i<20;$i++){//迴圈畫線
$linecolor=imagecolorallocate($img,mt_rand(0,250),mt_rand(0,250),mt_rand(0,250));
$linex=mt_rand(1,$width-1);
$liney=mt_rand(1,$height-1);
imageline($img,$linex,$liney,$linex+mt_rand(0,4)-2,$liney+mt_rand(0,4)-2,$linecolor);
}
for($i=0;$i<100;$i++){//迴圈畫點
$pointcolor=imagecolorallocate($img,mt_rand(0,250),mt_rand(0,250),mt_rand(0,250));
imagesetpixel($img,mt_rand(1,$width-1),mt_rand(1,$height-1),$pointcolor);
}
function getcode($length){//產生php隨機數
$pattern = '1234567890ABCDEFGHIJKLOMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ';//字元池
for($i=0;$i<$length;$i++) {
$key .= $pattern{mt_rand(0,35)};
}
return $key;

}
ob_clean();
header('Content-type:image/png');
imagepng($img);
?>

效果圖如下

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.