网站很多时候需要用到验证码,PHP生成验证码也很方便,这里用到了php的GD库,GD库,是php处理图形的扩展库,GD库提供了一系列用来处理图片的API,使用GD库可以处理图片,或者生成图片。
生成验证码的代码如下
public function actionGetVerifyCode() { $width = 80; $height = 36; $length = 4; $codelen = 4; //生成验证码 $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; //随机因子 $code = substr(str_shuffle($charset), 0, $codelen); //绘制图片 $width = ($length * 10 + 10) > $width ? $length * 10 + 10 : $width; $img = imagecreatetruecolor($width, $height); $r = array(225, 255, 255, 223); $g = array(225, 236, 237, 255); $b = array(225, 236, 166, 125); $key = mt_rand(0, 3); $backColor = imagecolorallocate($img, $r[$key], $g[$key], $b[$key]); //背景色(随机) $borderColor = imagecolorallocate($img, 100, 100, 100); //边框色 imagefilledrectangle($img, 0, 0, $width - 1, $height - 1, $backColor); imagerectangle($img, 0, 0, $width - 1, $height - 1, $borderColor); $stringColor = imagecolorallocate($img, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120)); //生成干扰素 for ($i = 0; $i < 5; $i++) { imagearc($img, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $stringColor); } for ($i = 0; $i < 25; $i++) { imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), $stringColor); } for ($i = 0; $i < $length; $i++) { imagestring($img, 10, $i * 20 + 5, mt_rand(1, 8), $code{$i}, $stringColor); } //输出图片 header("Content-type: image/png"); setcookie("validReg", md5(strtolower($code)), time() + 600, '/'); imagepng($img); imagedestroy($img); //返回验证码
使用验证码时,只要取cookie中的validReg即可
$cookieCode = isset($_COOKIE['validReg']) ? $_COOKIE['validReg'] : ""; $verifyCode = isset($_POST['verifyCode']) ? $_POST['verifyCode'] : ""; if ($cookieCode != md5(strtolower($verifyCode))) { $this->_processJson(array('errno' => -1, 'error' => '验证码错误')); return; }