php生成验证码

<?php

$rand_bg_file = './captcha/a.jpg';//设置背景地址

$img = imagecreatefromjpeg($rand_bg_file);//创建画布

$white = imagecolorallocate($img, 0xff, 0xff, 0xff);//绘制边框

imagerectangle($img, 0, 0, 144, 19, $white);//画一个无填充矩形

$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';//32 个字符,随机取出4个来当验证码

$captcha_str = '';

for($i=1,$strlen=strlen($chars); $i<=4; ++$i) {

	$rand_key = mt_rand(0, $strlen-1);

	$captcha_str .= $chars[$rand_key];

}

@session_start();

$_SESSION['captcha_code'] = $captcha_str;//将验证码值保存到session中

$black = imagecolorallocate($img, 0, 0, 0);//先确定颜色,白黑随机!

if(mt_rand(0, 1) == 1 ) {

	$str_color = $white;

} else {

	$str_color = $black;

}

imagestring($img, 5, 60, 3, $captcha_str, $str_color);//写入文字

header('Content-Type: image/jpeg; charset=utf-8');//告知浏览器,发送的是jpeg格式的图片

imagejpeg($img);//输出到浏览器端!

imagedestroy($img);//销毁资源

 

你可能感兴趣的:(PHP)