使用PHP

时间:2015-09-05 07:18:21

标签: php captcha

您好我想用创建一个图片验证码,我有我的表格的下一个代码。

<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> 

这是发送表单之前的验证代码:

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

在名为captcha.php的其他文件中,我有代码来生成图片:

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;

这会让图片显示来自img "Numeros aleatorios"的alt,以便告诉我file.php正在调用img,但生成的代码无效,任何帮助都很感激:D谢谢。

3 个答案:

答案 0 :(得分:1)

尝试更改:

$str .= $string{$pos};

$str .= $string[$pos]; //Array of strings.

我已经更新了我的回答:

<?php
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;
?>

在我的本地服务器中,验证码图像正确显示。

In my local server the captcha image is showing properly.

答案 1 :(得分:1)

您的代码很好,您唯一错过的就是在$str = ""文件的顶部声明catpcha.php

以下是您的代码的工作捕获:

enter image description here

更新

您的$string长度为36,因此您应该生成0到35之间的随机位置,如下所示:

$pos = rand(0,35);

如果没有,您有时会得到一张破损的图片和一条PHP通知。

更新N°2

您在没有声明$str = ""的情况下获得损坏图像的原因是因为此行

$str .= $string{$pos};

引发PHP通知并破坏图像。 (当然只有你 display_errors ,这就是为什么它对@Danny的服务器来说很完美)

答案 2 :(得分:0)

在captacha.php中使用此代码, 你可以试试这个:

<?php
@session_start();
header("Content-type: image/png");
$_SESSION["captcha"] = substr(md5(time()),0,5);
$im = imagecreate(110, 30);
$white = imagecolorallocate($im, 244, 255, 255);
$red = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$size = $_SESSION["captcha"];
$text = "$size";
$font = 'comic.TTF';
imagettftext($im, 20, 0, 25, 20, $red, $font, $text);
imagettftext($im, 20, 0, 25, 20, $black, $font, $text);
imagepng($im);
imagedestroy($im);
?>

图像字体样式需要comic.TTF这样的字体。

有关Captcha in PHP

的更多详情