php如何给表单添加验证码功能

Published
2023-08-11
浏览次数 :  72

创建验证码

<?php
session_start();

function generateRandomCode($length = 6) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $code;
}

$_SESSION['verification_code'] = generateRandomCode();
?>

在表格中展示验证码

<form method="post" action="process_form.php">
    <!-- Your other form fields here -->
    <label for="verification_code">Enter the verification code:</label>
    <input type="text" id="verification_code" name="verification_code" required>
    <img src="captcha_image.php" alt="Verification Code">
    <button type="submit">Submit</button>
</form>

生成验证码图片

在文件夹中新建captcha_image.php,复制粘贴以下代码:

<?php
session_start();

$verificationCode = $_SESSION['verification_code'];

header("Content-type: image/png");

$image = imagecreate(120, 40);
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);

imagestring($image, 5, 30, 12, $verificationCode, $textColor);

imagepng($image);
imagedestroy($image);
?>

服务器端验证

<?php
session_start();

$userEnteredCode = $_POST['verification_code'];
$storedCode = $_SESSION['verification_code'];

if ($userEnteredCode === $storedCode) {
    // Verification code is correct, process the form
} else {
    // Verification code is incorrect, show an error
}
?>

上面只是基础的代码显示如何用PHP来创建自定义验证码系统,但是安全系统不如reCAPTCHA这种专业的防机器人灌水的插件高。


标签:
Top