我正在尝试用PHP制作一个简单的验证码,我做错了什么


I am tring to make a simple captcha in PHP, what am I doing wrong?

我只是为了学习目的而尝试在 PHP 中制作一个简单的验证码,到目前为止还没有将字符串转换为图像,我不知道我做错了什么?我什至无法验证代码,它每次都给出字符串不匹配

这是代码

    <?php

    $var = 'abcdefghijklmnopqrstuywxyz1234567890';
    $random = str_shuffle($var);
    $captcha = substr($random,0,10);
    echo $captcha;

    if(isset($_POST['captcha'])){
    $check = $_POST['captcha'];
    if ($captcha==$check){
    echo 'Verified.';
    }else{echo 'string didn''t match';}
    }
    ?>
    <form action="random.php" method="POST">
    <input type="text" name="captcha"><br>
    <input type="submit" value="Submit">
    </form>

我不建议将其用于验证码。

但是我只是为了您的learning purpose而更正您的代码.

<?php
session_start();
if(isset($_POST['captcha'])){
$check = $_POST['captcha'];
if ($_SESSION['captcha']==$check){
echo 'Verified.';
}else{echo 'string didn''t match';}
}
$var = 'abcdefghijklmnopqrstuywxyz1234567890';
$random = str_shuffle($var);
$captcha = substr($random,0,10);
echo $captcha;
$_SESSION['captcha'] = $captcha;
?>
<form action="random.php" method="POST">
<input type="text" name="captcha"><br>
<input type="submit" value="Submit">
</form>

创建一个简单的验证码表单,那么这里有一个小指南:

===== 1 步 ====== 在您的 FTP 文件夹(您需要的位置)中,放置一个字体文件(例如:您的字体.ttf)。然后创建一个文件(称为CAPTCHA.php)并将以下代码粘贴到其中(然后将该CAPTCHA.php放在同一个FTP文件夹中):

<?php session_start();
// generate random number and store in session
$randomnr = rand(1000, 9999);
$_SESSION['randomnr2'] = md5($randomnr);
//generate image
$im = imagecreatetruecolor(100, 38);
//colors:
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 200, 35, $black);
// -------------      your fontname    -------------
//  example font http://www.webpagepublicity.com/free-fonts/a/Anklepants.ttf
$font = 'yourfont.ttf';
//draw text:
imagettftext($im, 35, 0, 22, 24, $grey, $font, $randomnr);
imagettftext($im, 35, 0, 15, 26, $white, $font, $randomnr);
// prevent client side  caching
header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revаlidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
//send image to browser
header ("Content-type: image/gif");
imagegif($im);
imagedestroy($im);
?>

===== 2 步 ======

然后在任何页面(你想要实现验证码的地方)将此代码放在该页面的某个地方(但当然,在本代码的最后一部分,如果代码输入正确,有一个示例 PHP 函数可以进行示例操作。所以你应该知道更多的PHP编程,以便在验证码正确时执行你想要的函数):

<form method="post" action=""> <img src="captcha.php" />
<input class="input" type="text" name="codee" />
<input type="submit" value="Submit" />
</form>
<?php
session_start();
if (md5($_POST['codee']) == $_SESSION['randomnr2']) { 
// here you  place code to be executed if the captcha test passes
  echo "YES. Do Something function1";
} 
else {  
 // here you  place code to be executed if the captcha test fails
  echo "No.  Do Something function2";
}
?>