写一段PHP代码用cookie与session实现登录
时间: 2023-06-14 14:07:39 浏览: 76
以下是一个简单的 PHP 代码示例,使用 cookie 和 session 实现登录功能:
<?php
session_start(); // 开启 session
// 检查是否已经登录
if(isset($_SESSION['username'])) {
echo "您已经登录,欢迎回来 {$_SESSION['username']}!";
exit;
}
// 如果提交了登录表单
if(isset($_POST['username']) && isset($_POST['password'])) {
// 验证用户名和密码
$username = $_POST['username'];
$password = $_POST['password'];
if($username === 'admin' && $password === '123456') {
// 验证通过,将用户信息存储到 session 中
$_SESSION['username'] = $username;
// 如果用户选择了记住我,则将用户名和密码存储到 cookie 中
if(isset($_POST['remember']) && $_POST['remember'] === 'on') {
setcookie('username', $username, time() + 3600 * 24 * 7); // 保存 7 天
setcookie('password', $password, time() + 3600 * 24 * 7);
}
// 跳转到首页
header('Location: index.php');
exit;
} else {
echo "用户名或密码错误!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form method="post" action="">
<label>用户名:<input type="text" name="username"></label><br>
<label>密码:<input type="password" name="password"></label><br>
<label><input type="checkbox" name="remember">记住我</label><br>
<button type="submit">登录</button>
</form>
</body>
</html>