我正在尝试在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>
答案 0 :(得分: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>
答案 1 :(得分:2)
要创建一个简单的Captcha表单,这里有一个小指南:
===== 1步====== 在你的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 STEP ======
然后在任何页面(你想要实现验证码的地方)把这个代码放在那个页面的某个地方(当然,在这段代码的最后一部分,有一个示例PHP函数,如果代码是正确输入。因此,当Captcha正确时,您应该知道更多的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";
}
?>
答案 2 :(得分:-1)
请使用类似akismet(http://akismet.com/)的内容而不是(构造不良)验证码。它们不是用户友好的,它们无法工作(或者无论如何都要长时间工作),而垃圾邮件发送者总是希望能够击败它们。