PHP学习- GD库生成简单的验证码

实验环境:wampserver集成开发环境包

源代码:

<?php
//简单使用GD绘制验证码   需要加载PHP_gd2.dll文件
// session_start();
/*
 * 功能:给出随机长度的字符
 * 参数 :
 * 		$len -给定字符串的长度
 * 输出:随机给定长度的字符串
 * */
header ( "content-type:image/gif" );
function random($len) {
	$srcstr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	$strs = "";
	for($i = 0; $i < $len; $i ++) {
		$strs .= $srcstr [mt_rand ( 0, 60 )];  //mt_rand 生成更好的随机数
	}
	//	return strtoupper ( $strs );  		//将字符串转化为大写字母
	return  $strs ;
}
$str = random ( 4 );
$width = 120;
$height = 35;

$image = imagecreate ( $width, $height );			//创建图像
$back = imagecolorallocate ( $image, 0xFF, 0xFF, 0xFF );	//设置背景颜色
$font = imagecolorallocate ( $image, 287, 330, 347 );		//绘制模糊作用点
$font_color = imagecolorallocate ( $image, mt_rand ( 50, 120 ), mt_rand ( 50, 120 ), mt_rand ( 50, 120 ) ); //设置字体颜色

for($i = 0; $i < 500; $i ++) {
	//画一个单一像素
	imagesetpixel ( $image, mt_rand ( 0, $width ), mt_rand ( 0, $height ), imagecolorallocate ( $image, mt_rand ( 1, 255 ), mt_rand ( 1, 255 ), mt_rand ( 1, 255 ) ) );
}
$font_file = $_SERVER['DOCUMENT_ROOT'].'arial.ttf'; //获取字体的文件位置
//设置字体的位置和颜色
imagettftext($image, mt_rand(15,28), mt_rand(-30,30), 5, 30, $font_color, $font_file, substr($str,0,1));
imagettftext($image, mt_rand(15,28), mt_rand(-30,30), 35, 30, $font_color, $font_file, substr($str,1,1));
imagettftext($image, mt_rand(15,28), mt_rand(-30,30), 65, 30, $font_color, $font_file, substr($str,2,1));
imagettftext($image, mt_rand(15,28), mt_rand(-30,30), 95, 30, $font_color, $font_file, substr($str,3,1));
imagerectangle($image, 0, 0, $width-1, $height-1, $font); 
imagepng($image);  		//显示
imagedestroy($image); 		//结束
?>

检测是否加载GD库的方法:

新建一个test.php文件

<?php
echo phpinfo();
?>

在浏览器中访问该文件的地址,查找是否存在下图内容:

如果存在,恭喜你!你已经能够成功运行上面的程序。

如果不存在上图内容:找到php的配置文件php.ini搜索gd关键词去掉前面的;



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值