Heim  >  Artikel  >  Backend-Entwicklung  >  php5 图片验证码的实例代码

php5 图片验证码的实例代码

WBOY
WBOYOriginal
2016-07-25 08:55:111026Durchsuche
  1. header("Content-type:image/jpeg")
复制代码

GD库中有对应的image类型 imagejpeg(),imagegif(),imagepang()

5,imageline画线函数 iamgeline(resource image,int x1,int y1,int x2,int y2,int color); image ---图片 x1 ---启始坐标 y1 x2 ---终点坐标 y2

6,imagesetpixel画点函数 imagesetpixel(resource image,int x,int y,int color)

7,imagettftext带字体的写入函数 imagettftext(resource image,float size,float angle,int x,int y,int color,string fontfile,string text)

8,php验证码插入中文的方法 iconv("gb2312","utf-8","字符串"); //首先要将文字转换成utf-8格式

9,随机函数 1,rand([int min,int max]) //rand(1,4) 生成1-4的数 2, dechex(十进制数) //转换为十六进制

以上介绍了php中gd库函数的一些常用方法,以及在php验证码中插入中文的方法,说到php验证码中显示中文的问题,大家可以参考之前介绍的 PHP中文汉字验证码(实例) 这篇文章。

另外,有兴趣的朋友,还可以研究下php 随机验证码与 php 图片验证码的实现方法,对于理解今天的例子,都会很有帮助的。

在php中,生成验证码的步骤: 生成随机数 -- 创建图片 -- 随机数写成图片 --保存在session中。

一,输入验证码 gdchek.php

  1. /*
  2. * 生成图片验证码
  3. * and open the template in the editor.
  4. */
  5. session_start();
  6. for($i=0;$i$rand.=dechex(rand(1,15)); //生成4位数包含十六进制的随机数
  7. }
  8. $_SESSION[check_gd]=$rand;
  9. $img=imagecreatetruecolor(100,30); //创建图片
  10. $bg=imagecolorallocate($img,0,0,0); //第一次生成的是背景颜色
  11. $fc=imagecolorallocate($img,255,255,255); //生成的字体颜色
  12. //给图片画线
  13. for($i=0;$i$te=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
  14. imageline($img,rand(0,15),0,100,30,$te);
  15. }
  16. //给图片画点
  17. for($i=0;$i$te=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
  18. imagesetpixel($img,rand()%100,rand()%30,$te);
  19. }
  20. //首先要将文字转换成utf-8格式
  21. //$str=iconv("gb2312","utf-8","呵呵呵");
  22. //加入中文的验证 bbs.it-home.org
  23. //smkai.ttf是一个字体文件,为了在别人的电脑中也能起到字体作用,把文件放到项目的根目录,可以下载,还有本机C:\WINDOWS\Fonts中有
  24. imagettftext($img,11,10,20,20,$fc,"simkai.ttf","你好你好");
  25. //把字符串写在图片中
  26. //imagestring($img,rand(1,6),rand(3,70),rand(3,16),$rand,$fc);
  27. //输出图片
  28. header("Content-type:image/jpeg");
  29. imagejpeg($img);
  30. ?>
复制代码

2,登录页面 login.php

  1. /*
  2. * 验证登录,用到了验证码
  3. */
  4. session_start();
  5. if($_POST[sub]){
  6. //判断验证码是否相同
  7. if($_POST[gd_pic]==$_SESSION[check_gd]){
  8. echo "验证成功!";
  9. }else{
  10. echo "验证码错误";
  11. }
  12. }
  13. ?>
  14. 用户名:
  15. 密码:
  16. 验证码:php5 图片验证码的实例代码
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn