PHP - 登录示例
典型的 PHP Web 应用程序在用户登录前会进行身份验证,通过询问用户的凭据如 username 和 password。然后将这些凭据与服务器上可用的用户数据进行比对。在本示例中,用户数据以关联数组的形式提供。下面的 PHP 登录脚本将逐一解释 —
HTML 表单
代码的 HTML 部分呈现了一个简单的 HTML 表单,它接受 username 和 password,并将数据 post 到自身。
<form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<div>
<label for="username">Username:</label>
<input type="text" name="username" id="name">
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<section style="margin-left:2rem;">
<button type="submit" name="login">Login</button>
</section>
</form>
PHP 身份验证
PHP 脚本解析 POST 数据,并检查 username 是否存在于 users 数组中。如果找到,则进一步检查 password 是否与数组中注册的用户匹配
<?php
if (array_key_exists($user, $users)) {
if ($users[$_POST['username']]==$_POST['password']) {
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
$_SESSION['username'] = $_POST['username'];
$msg = "您输入的 username 和 password 正确";
} else {
$msg = "您输入的 Password 错误";
}
} else {
$msg = "您输入的 user name 错误";
}
?>
username 和相应的消息被添加到 $_SESSION 数组中。用户会收到相应的提示消息,告知其输入的凭据是否正确。
完整代码
以下是完整代码 −
Login.php
<?php
ob_start();
session_start();
?>
<html lang = "en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="loginstyle.css">
<title>Login</title>
</head>
<body>
<h2 style="margin-left:10rem; margin-top:5rem;">Enter Username and Password</h2>
<?php
$msg = '';
$users = ['user'=>"test", "manager"=>"secret", "guest"=>"abc123"];
if (isset($_POST['login']) && !empty($_POST['username'])
&& !empty($_POST['password'])) {
$user=$_POST['username'];
if (array_key_exists($user, $users)){
if ($users[$_POST['username']]==$_POST['password']){
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
$_SESSION['username'] = $_POST['username'];
$msg = "You have entered correct username and password";
}
else {
$msg = "You have entered wrong Password";
}
}
else {
$msg = "You have entered wrong user name";
}
}
?>
<h4 style="margin-left:10rem; color:red;"><?php echo $msg; ?></h4>
<br/><br/>
<form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<div>
<label for="username">Username:</label>
<input type="text" name="username" id="name">
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<section style="margin-left:2rem;">
<button type="submit" name="login">Login</button>
</section>
</form>
<p style="margin-left: 2rem;">
<a href = "logout.php" tite = "Logout">Click here to clean Session.</a>
</p>
</div>
</body>
</html>
Logout.php
要登出,用户点击logout.php的链接
<?php
session_start();
unset($_SESSION["username"]);
unset($_SESSION["password"]);
echo '<h4>You have cleaned session</h4>';
header('Refresh: 2; URL = login.php');
?>
通过输入 "http://localhost/login.php" 启动应用程序。以下是不同场景 −
正确的用户名和密码
错误的密码
错误的用户名
当用户点击底部的链接时,session 变量将被移除,登录界面将重新出现。