A-A+

php生成动态的图片随机码,可指定画布大小

2019年10月22日 PHP技术文章 评论 2 条 阅读 0 views 次

PHP验证码在注册或者登陆的时候是必不可少的,主要是为了防止垃圾注册或者恶意登陆,在TP系统中有内置的生成验证码的类,直接调用就可以了,而在PHP的原生代码中,则需要使用 image 之类的函数,使用 imagecreate 来进行画布的创建,其实如果我们要扒开TP图片类的话,也是使用了PHP的函数类来创建的,好了,我们先看一下PHP生成动态随机码的方法吧,可以自行指定图片的大小,其中使用了创建画布 imagecreate 函数和 随机码的函数 mt_rand 等等,代码如下:

  1. $image_width = 100;  
  2.   
  3. $image_height = 100;  
  4.   
  5. $image_str = '';  
  6.   
  7. if (isset($_GET['w']))  
  8.   
  9. {  
  10.   
  11.   $image_width = intval($_GET['w']);  
  12.   
  13. }  
  14.   
  15. if (isset($_GET['h']))  
  16.   
  17. {  
  18.   
  19.   $image_height = intval($_GET['h']);  
  20.   
  21. }  
  22.   
  23. if (isset($_GET['s']))  
  24.   
  25. {  
  26.   
  27.   $image_str = $_GET['s'];  
  28.   
  29. }  
  30.   
  31. $img = imagecreate($image_width$image_height);  
  32.   
  33. $color = imagecolorallocate($img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));  
  34.   
  35. imagefilledrectangle($img, 0, $image_height$image_width, 0, $color);  
  36.   
  37. $step = mt_rand(15, 30);  
  38.   
  39. $start = mt_rand(0, $step);  
  40.   
  41. $color = imagecolorallocate($img, mt_rand(200,255), mt_rand(200,255), mt_rand(200,255));  
  42.   
  43. imagesetthickness($img, mt_rand(3, 10));  
  44.   
  45. if ($image_height > $image_width)  
  46.   
  47. {  
  48.   
  49.   for ($i=$start$i<$image_height * 2; $i+=$step)  
  50.   
  51.   {  
  52.   
  53.     imageline($img, 0, $i$i, 0, $color);  
  54.   
  55.   }  
  56.   
  57. }  
  58.   
  59. else  
  60.   
  61. {  
  62.   
  63.   for ($i=$start$i<$image_width * 2; $i+=$step)  
  64.   
  65.   {  
  66.   
  67.     imageline($img$i, 0, 0, $i$color);  
  68.   
  69.   }  
  70.   
  71. }  
  72.   
  73. if ($image_str != '')  
  74.   
  75. {  
  76.   
  77.   $black = imagecolorallocate($img, 0, 0, 0);  
  78.   
  79.   imagestring($img, 12, 5, 5, $image_str$black);  
  80.   
  81. }  
  82.   
  83. header('Content-type:image/png');  
  84. //www.xiariboke.net  
  85. imagepng($img);  
  86.   
  87. imagedestroy($img);  

一段很简单的PHP生成动态随机码的代码,代码有点粗糙,但是比较容易理解,如果是简单的应用,可以封装成一个图片验证码类,在使用的时候直接进行调用就OK了。

标签:

2 条留言  访客:2 条  博主:0 条

  1. 策意智库

    欢迎来访!博客做的不错!

  2. sheruo

    来看看,不知道能不能加个连接哈。

给我留言