dongwenhui8900 2015-09-05 07:18 采纳率: 0%
浏览 41
已采纳

使用PHP创建图像验证码

Hi i want to create a image captcha with php, i have the next code for my form.

<form action="" method="POST">
    <div class="label_form">Usuario:</div> <input type="text" name="user"/><br>
    <div class="label_form">Contraseña:</div> <input type="password" name="pass"/><br>  
    <img alt="Numeros aleatorios" src="layouts/captcha.php" />  
    <input class="label_form" type="text" name="num"/><br>
    <input type="submit" value="ENTRAR" name="submit"/>
</form> 

This is the code for validation before to send the form:

if (isset($_POST["submit"])) {
  if ($_SESSION['img_number'] != $_POST['num']) {
    echo "<div class='msg_error'>Los caracteres no se corresponden.</div>";
  } else {
    /*DO STUFF*/
  }
}

And in other file with the name captcha.php i have the code phpfor generate the image:

header("Content-type: image/png");
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for ($i = 0; $i < 5; $i++) {
  $pos = rand(0, 36);
  $str. = $string {
    $pos
  };
}
$img_handle = ImageCreate(60, 22) or die("Es imposible crear la imagen");
$back_color = ImageColorAllocate($img_handle, 102, 102, 153);
$txt_color = ImageColorAllocate($img_handle, 255, 255, 255);
ImageString($img_handle, 31, 5, 0, $str, $txt_color);
Imagepng($img_handle);
session_start();
$_SESSION['img_number'] = $str;

This give a image broken showing the alt from img "Numeros aleatorios", so that tell me the file.php is calling fine the img but the code for generated is not working, any help is gratefull :D thanks.

  • 写回答

3条回答 默认 最新

  • doutandusegang2961 2015-09-05 14:33
    关注

    Your code is good the only thing you missed is declaring $str = "" at the top of your catpcha.php file

    Here is a working capture of your code:

    enter image description here

    Update

    Your $string length is 36, so you should generate a random position between 0 and 35, like this:

    $pos = rand(0,35);
    

    If not, you sometimes get a broken image and a PHP Notice.

    Update N°2

    The reason why you get a broken image without declaring $str = "" is because this line

    $str .= $string{$pos};
    

    Throws a PHP Notice and corrupts the image. (Of course only if you display_errors , that's why it worked perfectly for @Danny's server)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵