- <?php
- class captcha {
- public static function generate($width,$height){
- $char_arr = array_merge(range('a','z'),range('A','Z'),range(1,9));
- $rand_keys = array_rand($char_arr,4);
- shuffle($rand_keys);
- $rand_str = ''; //設置初始值
- foreach($rand_keys as $key ){
- $rand_str .= $char_arr[$key]; // 注意是 .=
- }
- //將 $rand_str保存到 session中
- $_SESSION['captcha_code'] = $rand_str;
- $img = p_w_picpathcreatetruecolor($width,$height);
- //增長背景顏色
- $back_color = p_w_picpathcolorallocate($img, mt_rand(160,250), mt_rand(150,240), mt_rand(150,250));
- p_w_picpathfill($img, 0, 0, $back_color);
- //增長像素點
- $pixel_color = p_w_picpathcolorallocate($img, mt_rand(95,190), mt_rand(95,190), mt_rand(95,190));
- for($i=0;$i<40;$i++){
- p_w_picpathsetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$pixel_color);
- }
- //增長線條
- $line_color = p_w_picpathcolorallocate($img, mt_rand(95,190), mt_rand(95,190), mt_rand(95,190));
- for($i=0;$i<3;$i++){
- p_w_picpathline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$line_color);
- }
- //在圖片上面 添加字體,設置字體顏色
- $str_color = p_w_picpathcolorallocate($img, mt_rand(0,150), mt_rand(0,100), mt_rand(0,140));
- p_w_picpathstring($img, 5, 58, 3, $rand_str, $str_color);
- //顯示圖片
- header("content-type:p_w_picpath/png");
- p_w_picpathpng($img);
- //銷燬圖片
- p_w_picpathdestroy($img);
- }
- public static function checkCode($str){
- if(strtoupper($_SESSION['captcha_code']) == strtoupper($str)){
- return true;
- }else {
- return false;
- }
- }
- }
- //captcha::generate(145, 20);
- ?>