<?php session_start(); //產生一個隨機的字符串驗證碼 $checkcode=""; for ($i=0;$i<4;$i++){ $checkcode.=dechex(rand(0,15)); //string dechex ( int $number ) 返回一字符串,包含有給定 number 參數的十六進制表示 } //將隨機驗證碼保存到session中 $_SESSION['myCheckCode']=$checkcode; //創建圖片,並把上面產生的隨機驗證碼畫上去 $img=imagecreatetruecolor(100, 20); //背景默認是黑色,可以自己設定背景顏色 $bgcolor=imagecolorallocate($img, 0, 0, 0); //imagefill() 在 image 圖像的坐標 x,y(圖像左上角為 0, 0)處用 color 顏色執行區域填充(即與 x, y 點顏色相同且相鄰的點都會被填充)。 imagefill($img, 0, 0, $bgcolor); //創建新的顏色 imagecolorallocate — 為一幅圖像分配顏色 //imagecolorallocate() 返回一個標識符,代表了由給定的 RGB 成分組成的顏色。 //red,green 和 blue 分別是所需要的顏色的紅,綠,藍成分。這些參數是 0 到 255 的整數或者十六進制的 0x00 到 0xFF。 //imagecolorallocate() 必須被調用以創建每一種用在 image 所代表的圖像中的顏色 $white=imagecolorallocate($img, 255, 255, 255); $blue=imagecolorallocate($img, 0, 0, 255); $red=imagecolorallocate($img, 255, 0, 0); $green=imagecolorallocate($img, 255, 0, 0); //畫出干擾線段 /*for($i=0;$i<10;$i++){ //bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) //imageline() 用 color 顏色在圖像 image 中從坐標 x1,y1 到 x2,y2(圖像左上角為 0, 0)畫一條線段。 imageline($img, rand(0, 100), rand(0, 20), rand(0, 100), rand(0, 20), imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255))); }*/ //畫出噪點 //for(){} //把上面產生的四個隨機值,字符串畫上去 //bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col ) //imagestring() 用 col 顏色將字符串 s 畫到 image 所代表的圖像的 x,y 坐標處(這是字符串左上角坐標,整幅圖像的左上角為 0,0)。 //如果 font 是 1,2,3,4 或 5,則使用內置字體。 imagestring($img, rand(2, 5), rand(2, 60), rand(2, 5), $checkcode, $white); header("content-type:image/png"); //imagepng() 將 GD 圖像流(image)以 PNG 格式輸出到標准輸出(通常為瀏覽器),或者如果用 filename 給出了文件名則將其輸出到該文件。 imagepng($img); ?>
效果如下圖,每次刷新都會隨機生成一個:
第二次刷新:
在頁面顯示:
<div>驗證碼:<input type="text"><img src="上邊的代碼地址" onclick="javascript:this.src='上邊的代碼地址?tm='+Math.random()"></div>
點擊圖片可以進行切換