帮我写一份PHP登陆代码
时间: 2023-08-28 07:36:32 浏览: 44
好的,以下是一个简单的PHP登录代码示例,供您参考:
```php
<?php
session_start(); // 启动会话
// 判断是否提交了表单
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// 验证用户名和密码是否正确
if ($username === 'admin' && $password === '123456') {
// 登录成功,将用户信息存储到会话中
$_SESSION['username'] = $username;
header('location: index.php'); // 跳转到首页
exit;
} else {
// 登录失败,显示错误信息
$error = '用户名或密码错误';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<?php if (isset($error)) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="username">用户名:</label>
<input type="text" name="username" required><br><br>
<label for="password">密码:</label>
<input type="password" name="password" required><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
这个示例代码中包含一个表单,用户需要输入用户名和密码。当用户提交表单时,代码会验证用户名和密码是否正确,如果正确,则将用户信息存储到会话中,并跳转到首页;如果错误,则显示错误信息。