在网站开发中,为了提高安全性和用户体验,我们通常会在登录表单中加入验证码功能,验证码可以有效防止恶意破解密码、暴力破解等行为,本文将介绍如何在PHP中实现验证码登录功能。
准备工作
1、创建一个HTML文件,用于显示登录表单,包括用户名、密码输入框和验证码图片。
<!DOCTYPE html>
<html>
<head>
    <title>验证码登录</title>
</head>
<body>
    <form action="check_login.php" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        验证码:<input type="text" name="captcha"><br>
        <img src="captcha.php" alt="验证码"><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>
2、创建一个PHP文件,用于生成验证码图片。
<?php
session_start();
header("Content-type: image/png");
$width = 100;
$height = 30;
$image = imagecreate($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= chr(rand(65, 90));
}
$_SESSION['captcha'] = $code;
imagestring($image, 5, 30, 8, $code, $textColor);
imagepng($image);
imagedestroy($image);
?>
验证登录信息
1、创建一个PHP文件,用于验证登录信息,首先获取用户输入的验证码,然后与服务器端生成的验证码进行比较,如果相同,则继续验证用户名和密码,这里我们假设已经有一个用户数据表(user),包含用户名(username)和密码(password)。
<?php
session_start();
require_once 'config.php'; // 引入数据库连接配置
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['captcha'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $captcha = $_POST['captcha'];
    if ($captcha == $_SESSION['captcha']) { // 验证验证码是否正确
        $sql = "SELECT * FROM user WHERE username = '$username' AND password = '$password'";
        $result = mysqli_query($conn, $sql);
        if (mysqli_num_rows($result) > 0) { // 如果查询到用户数据,说明登录成功
            echo "登录成功!";
        } else { // 如果查询不到用户数据,说明用户名或密码错误
            echo "用户名或密码错误!";
        }
    } else { // 如果验证码不正确,提示用户重新输入验证码
        echo "验证码错误,请重新输入!";
    }
} else { // 如果缺少必要的表单字段,提示用户填写完整信息
    echo "请填写完整的登录信息!";
}
?>
通过以上步骤,我们就实现了一个简单的PHP验证码登录功能,在实际开发中,还需要考虑更多的安全性问题,例如使用安全的加密算法存储密码、对用户输入进行过滤和校验等。




 
		 
		 
		
还没有评论,来说两句吧...