溫馨提示×

php怎么制作驗證碼登錄頁面

PHP
小億
83
2024-06-05 17:18:29
欄目: 編程語言

要制作驗證碼登錄頁面,可以按照以下步驟進行:

  1. 創(chuàng)建一個包含驗證碼生成和校驗功能的PHP文件。可以使用GD庫來生成驗證碼圖片,并將生成的驗證碼存儲在Session中用于校驗。
<?php
session_start();

$width = 100;
$height = 30;

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$char_length = strlen($characters);

$code = '';
for ($i = 0; $i < 6; $i++) {
    $code .= $characters[rand(0, $char_length - 1)];
}

$_SESSION['captcha_code'] = $code;

$image = imagecreatetruecolor($width, $height);
$bg_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);

imagefill($image, 0, 0, $bg_color);
imagestring($image, 5, 40, 10, $code, $text_color);

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
  1. 創(chuàng)建一個包含登錄表單的HTML文件,其中包含一個驗證碼輸入框和一個用來顯示驗證碼圖片的img標簽。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Captcha Login</title>
</head>
<body>
    <h2>Login Form</h2>
    <form action="login.php" method="post">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" required><br><br>
        
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required><br><br>
        
        <label for="captcha">Captcha:</label>
        <input type="text" name="captcha" id="captcha" required><br><br>
        
        <img src="captcha.php" alt="captcha"><br><br>
        
        <input type="submit" value="Login">
    </form>
</body>
</html>
  1. 創(chuàng)建一個用于校驗登錄信息的PHP文件,驗證用戶名、密碼和驗證碼是否匹配。
<?php
session_start();

$username = $_POST['username'];
$password = $_POST['password'];
$captcha = $_POST['captcha'];

if ($username == 'admin' && $password == 'password' && $captcha == $_SESSION['captcha_code']) {
    echo 'Login successful';
} else {
    echo 'Login failed';
}
?>

通過以上步驟,就可以實現(xiàn)一個帶有驗證碼的登錄頁面。當用戶輸入用戶名、密碼和驗證碼后,點擊登錄按鈕,系統(tǒng)會校驗用戶輸入的信息是否正確,并給出相應的提示。

0