GetVerifyImg.php <?php session_start(); /* *功能:生成随机字符串 *@para: $length 字符串长度 *@return: array 随机字符串数组 */ function getVerify($length) { $string = array('1','2','3','4','5','6','7','8','9','0','q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','c','v','b','n','m','Q','W','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'); $chNum = ""; $count = count($string); for($i = 0; $i < $length; $i++) { $chNum .= $string[rand(0,$count-1)]; } return $chNum; } $length = 4; //定义字符串长度 $strNum = getVerify($length); //生成随机4位字符串 $_SESSION['verify'] = $strNum; // 赋值给SESSION $width = 73; //图片宽度 $height = 24; //图片高度 $fontSize = 15; //字体大小 $img = imagecreate($width, $height); //生成指定宽高的图片 $backgroundColor = imagecolorallocate($img, 255, 255, 255); $font = realpath("arial.ttf"); for($i = 0; $i < $length; $i++) { $charX = $i * 15 + 8; //定义X坐标 $charY = ($i + 33) / 2 + rand(-1, 1); //定义Y坐标 $textColor = imagecolorallocate($img, mt_rand(50, 200), mt_rand(50, 128), mt_rand(50, 200)); $angel = rand(-20, 20); //生成字符角度 //写入字符 imagettftext($img, $fontSize, $angel, $charX, $charY, $textColor, $font, $strNum[$i]); } for($i = 0; $i <= 5; $i++) {//循环画背景线 $lineColor = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); $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 <= 32; $i++){//循环生成麻点效果 $pointColor = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagesetpixel($img, mt_rand(1, $width - 1), mt_rand(1, $height - 1), $pointColor); } //画边框 $frameColor = imagecolorallocate($img, 150, 150, 150); imagerectangle($img, 0, 0, $width - 1, $height - 1, $frameColor); ob_clean(); header("Content-type: image/png"); //header('Cache-control: no-cache'); // not to cache imagepng($img); imagedestroy($img); ?>