写一份这样的代码,通过手动输入验证码作为登陆,并在3天内不需要再次输入
时间: 2024-03-17 14:47:10 浏览: 15
这里提供一个 PHP 实现的代码示例,可以实现手动输入验证码作为登陆,并在 3 天内不需要再次输入验证码的功能。具体实现方式如下:
1. 在登陆页面中加入一个验证码输入框和一个“记住我”选项框。
```html
<form method="post" action="login.php">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="text" name="captcha" placeholder="Enter the captcha" required>
<img src="captcha.php" alt="Captcha">
<input type="checkbox" name="remember" value="1">Remember me
<button type="submit">Login</button>
</form>
```
2. 在后端 PHP 中生成验证码图片和验证码,并将验证码保存到 session 中。
```php
<?php
session_start();
// 生成随机验证码
$captcha = '';
$length = 6;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characters_length = strlen($characters);
for ($i = 0; $i < $length; $i++) {
$captcha .= $characters[rand(0, $characters_length - 1)];
}
// 保存验证码到 session 中
$_SESSION['captcha'] = $captcha;
// 生成验证码图片
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $width, $height, $background_color);
imagettftext($image, 20, 0, 10, 25, $text_color, 'arial.ttf', $captcha);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
```
3. 在后端 PHP 中验证验证码是否正确,并将“记住我”选项保存到 cookie 中。
```php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 验证验证码
if ($_POST['captcha'] == $_SESSION['captcha']) {
// 验证成功
// 将“记住我”选项保存到 cookie 中,过期时间为 3 天
if ($_POST['remember'] == '1') {
setcookie('remember', '1', time() + 3 * 24 * 60 * 60);
}
// 其他登陆验证逻辑
// ...
} else {
// 验证失败
// ...
}
}
?>
```
4. 在登陆页面中判断是否需要显示验证码,并在“记住我”选项被选中的情况下,将验证码保存到 cookie 中。
```php
<?php
session_start();
// 判断是否需要显示验证码
if (isset($_COOKIE['remember']) && $_COOKIE['remember'] == '1') {
$captcha = isset($_COOKIE['captcha']) ? $_COOKIE['captcha'] : '';
} else {
$captcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : '';
}
// 保存验证码到 cookie 中
if (isset($_POST['remember']) && $_POST['remember'] == '1') {
setcookie('captcha', $_SESSION['captcha'], time() + 3 * 24 * 60 * 60);
}
// 其他页面代码
// ...
?>
```
需要注意的是,这只是一个简单的示例代码,实际应用中还需要加入更多的安全措施,如检查用户输入的验证码是否合法,防止 XSS 和 CSRF 攻击等。