-3

我正在尝试在 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>
4

2 回答 2

4

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

但我只为您的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>
于 2012-08-07T09:03:52.567 回答
2

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

===== 1 STEP ====== 在您的 FTP 文件夹(您需要的位置)中,放置一个字体文件(例如:yourfont.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";
}
?>
于 2013-03-26T09:35:26.247 回答