我们需要生成一个随机字符串(文本),将其存储在会话中以检查 $_POST,使用该字符串创建图像,在表单上显示图像,然后在提交时检查它。
步骤 1. 创建一个随机字符串并将其保存在 $_SESSION 这一步非常简单,因为 PHP 具有我们需要的所有功能。生成随机字符串的一种快速有效的方法是使用 rand 函数,对其进行 md5 加密,然后提取您喜欢的字符数量。
代码:
<?php
session_start(); // Very important.
$captcha = md5(uniqid(rand(), true)); // Generate our random string.
$captcha = substr($captcha,0,6);
$_SESSION['captchaCode'] = $captcha; // Save the captch code to a session.
echo $captcha; // echo a generated code for testing purposes
?>
将上面的内容保存到“captcha.php”,然后看看它生成了什么。资源:http : //www.php.net/md5、http : //www.php.net/rand、http: //www.php.net/substr、http : //www.php.net/uniqid
步骤 2. 从生成的字符串创建图像 有许多不同的方法可以做到这一点,例如使用 GD 库 (gd libs),但我更喜欢使用 ImageMagick 进行图像处理 - 个人选择。
请注意:ImageMagick 和 GD Libs 默认不附带 PHP,请检查它们是否安装在您的服务器上。
首先我们需要背景图片(附在这个帖子上 - 请将它们存储在 images/ 文件夹中) - “bg1.png”、“bg2.png”和“bg3.png” 每次生成图片时它会随机选择一个背景图片. 我们将文件名存储在一个易于访问的数组中。使用 ImageMagick 时,您应该上传要使用的所需字体,这意味着在不同的服务器上它将始终能够使用您的字体。
所以我们现在有以下代码。代码:
<?php
session_start(); // Very important.
$captcha = md5(uniqid(rand(), true)); // Generate our random string.
$captcha = substr($captcha,0,6);
$_SESSION['captchaCode'] = $captcha; // Save the captch code to a session.
//echo $captcha; // echo a generated code for testing purposes
$imageDirectory = 'images/'; // The relative or absolute path to where images are stored.
$bgImages = array('bg1.png', 'bg2.png', 'bg3.png');
$backgroundImage = $imageDirectory.$bgImages[rand(0, count($bgImages)-1)]; // This chooses an image.
?>
现在是复杂的部分,实际上将它们放在一起 - 但别担心,我会尽可能多地评论所有内容。
代码:
<?php
session_start(); // Very important.
$captcha = md5(uniqid(rand(), true)); // Generate our random string.
$captcha = substr($captcha,0,6);
$_SESSION['captchaCode'] = $captcha; // Save the captch code to a session.
//echo $captcha; // echo a generated code for testing purposes
$imageDirectory = 'images/'; // The relative or absolute path to where images are stored.
$bgImages = array('bg1.png', 'bg2.png', 'bg3.png');
$backgroundImage = $imageDirectory.$bgImages[rand(0, count($bgImages)-1)]; // This chooses an image.
$tmpFilename = $captcha . '.png'; // Use the captcha code to create a random filename - Please note this filename is not shown in the user's web browser.
$imageTmpDirectory = 'images/tmp/'; //Directory to store all tmp generated images.
$font = 'arial.ttf'; // The chosen font - this font sits in the same folder as this script.
$FontSize = rand(24, 36); // Random select a font size between 24 and 36.
$hexValues = array('0','1','2','3','4'); // Hex values, we always want dark colours hence 0 to 5.
$numHex = count($hexValues); // Count how many hex values.
$GeneratedHex = ''; // Set the variable.
for ($i = 0; $i < 6; $i++) {
$GeneratedHex .= $hexValues[rand(0, $numHex-1)]; // Generate the end hex colour.
}
$gravities = array('West', 'Center', 'East'); // ImageMagicks gravity function.
$gravity = $gravities[rand(0, count($gravities)-1)]; // Choose a gravity.
$angle = rand(-5, 5); // Generate an angle for the text.
$cmd = '/usr/bin/convert'; // Path to ImageMagick on the server.
$cmd .= ' -font '.$font; // The generated colour.
$cmd .= ' -fill "#'.$GeneratedHex.'"'; // The generated colour.
$cmd .= ' -pointsize '.$FontSize ; // The size.
$cmd .= ' -gravity "'.$gravity.'"'; // Select generated gravity.
$cmd .= ' -draw \'text 0,0 "'.$captcha.'"\''; // Draw the captcha.
$cmd .= ' -rotate '.$angle; // Rotate the text to the generated angle.
$cmd .= ' ./'.$backgroundImage.' ./'.$imageTmpDirectory.$tmpFilename; // Assign background image and then save output.
exec($cmd); // Run the command!
header('Content-Type: image/png');
print fread(fopen($imageTmpDirectory.$tmpFilename, 'r'), filesize($imageTmpDirectory.$tmpFilename));
unlink($imageTmpDirectory.$tmpFilename); // Delete the tmp image.
?>
当您运行上述代码时,您应该会看到如下内容: Image
步骤 3. 在表单中使用验证码。好吧,最困难的部分现在结束了!从这里开始变得更容易!
我们需要做的就是在 img 标签中加载验证码脚本,例如
这是表单页面。代码:
<?php
session_start(); // Very important to be the first statement. ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="capturePost.php" method="post">
<?php
if(!empty($_SESSION['ERROR'])) { // We have an error from capturePost.php
echo '<p>' . $_SESSION['ERROR'] . '</p>'; // Display error.
unset($_SESSION['ERROR']); // Clear error.
}?>
<img src="captcha.php" alt="Captcha Code"><br />
Please enter the security code <input type="text" name="captcha">
<br /><input type="submit">
</form>
</body>
</html>
这是提交页面(capturePost.php)的代码:
<?php
session_start();
if(!empty($_POST['captcha'])) {
if($_POST['captcha'] != $_SESSION['captchaCode']) { // see if the code is incorrect.
$_SESSION['ERROR'] = '<strong>Code did not match, please try again.</stong>'; // Our error message.
header('Location: ' . $_SERVER['HTTP_REFERER']); // Take them back to form page.
} else {
echo 'Well done, you entered the correct code'; // Its correct!
// DO FORM PROCESSING HERE
}
}
?>
我真的希望这会有所帮助。