zoukankan      html  css  js  c++  java
  • php编写验证码

    今天学习到了php登录时的验证码,验证码在我们平时的网站建设中是非常重要的,对于放置一些灌水机、脚本攻击是一个很好地策略。

    下面是我写的代码:

     1 <?php
     2 session_start();
     3 //产生一个随机的字符串验证码
     4 $checkcode="";
     5 for ($i=0;$i<4;$i++){
     6  $checkcode.=dechex(rand(0,15)); //string dechex ( int $number ) 返回一字符串,包含有给定 number 参数的十六进制表示
     7 }
     8 //将随机验证码保存到session中
     9 $_SESSION['myCheckCode']=$checkcode;
    10 //创建图片,并把上面产生的随机验证码画上去
    11 $img=imagecreatetruecolor(100, 20);
    12 //背景默认是黑色,可以自己设定背景颜色
    13 $bgcolor=imagecolorallocate($img, 0, 0, 0);
    14 //imagefill() 在 image 图像的坐标 x,y(图像左上角为 0, 0)处用 color 颜色执行区域填充(即与 x, y 点颜色相同且相邻的点都会被填充)。
    15 imagefill($img, 0, 0, $bgcolor);
    16 //创建新的颜色 imagecolorallocate — 为一幅图像分配颜色
    17 //imagecolorallocate() 返回一个标识符,代表了由给定的 RGB 成分组成的颜色。
    18 //red,green 和 blue 分别是所需要的颜色的红,绿,蓝成分。这些参数是 0 到 255 的整数或者十六进制的 0x00 到 0xFF。
    19 //imagecolorallocate() 必须被调用以创建每一种用在 image 所代表的图像中的颜色
    20 $white=imagecolorallocate($img, 255, 255, 255);
    21 $blue=imagecolorallocate($img, 0, 0, 255);
    22 $red=imagecolorallocate($img, 255, 0, 0);
    23 $green=imagecolorallocate($img, 255, 0, 0);
    24 //画出干扰线段
    25 for($i=0;$i<10;$i++){
    26  //bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
    27  //imageline() 用 color 颜色在图像 image 中从坐标 x1,y1 到 x2,y2(图像左上角为 0, 0)画一条线段。
    28  imageline($img, rand(0, 100), rand(0, 20), rand(0, 100), rand(0, 20), imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255)));
    29 }
    30 //画出噪点
    31 //for(){}
    32 //把上面产生的四个随机值,字符串画上去
    33 //bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )
    34 //imagestring() 用 col 颜色将字符串 s 画到 image 所代表的图像的 x,y 坐标处(这是字符串左上角坐标,整幅图像的左上角为 0,0)。
    35 //如果 font 是 1,2,3,4 或 5,则使用内置字体。
    36 imagestring($img, rand(2, 5), rand(2, 60), rand(2, 5), $checkcode, $white);
    37 header("content-type:image/png");
    38 //imagepng() 将 GD 图像流(image)以 PNG 格式输出到标准输出(通常为浏览器),或者如果用 filename 给出了文件名则将其输出到该文件。
    39 imagepng($img);
    40 ?>
    A dwarf on a giant's shoulder sees the farther of the two. 站在巨人肩上的矮子看得比巨人远。 --A dwarf on a giant's shoulders
  • 相关阅读:
    第五周总结
    第四周总结
    关于“模仿"和”创新“
    第三周总结
    第九周总结
    第八周总结
    第六周总结
    中国历史上成功的两人合作
    第五周总结
    第四周总结
  • 原文地址:https://www.cnblogs.com/wxb0328/p/php.html
Copyright © 2011-2022 走看看