我正在寻找一个 php 脚本,因此我的整个网站需要密码才能访问。我不需要 sql 数据库,我只想要一个在变量中设置凭据的用户。
我有
配置.php
<?php
$secured = false;
$username = "user"; // Set manually by editing config
$password = "pass"; //Set manually by editing config
?>
然后是index.html
<form action="auth.php" method="post">
Username: <input type='text' name="user" value='' />
Password: <input type='password' name="password" value='' />
<input type='submit' value='Log in' />
</form>
然后是 auth.php (这是我需要编码的)
<?php
require once "config.php"
If $secured = false the redirect to page1.html
//因此,如果其为 false,则无需在站点上的任何位置进行身份验证。
If $secured = true then ask for username and password.
If wrong display error message.
If right redirect to page1.html
?>
这就是我想要实现的目标。然后,我还需要将登录名存储为 session 变量,以便它记住您登录并检查您登录的每个页面。最后是一种注销方法。所以我只要把一个按钮贴在某个地方就可以完成这项工作。希望这一切都有道理。
问题:auth.php 脚本是什么样的?
谢谢
最佳答案
您可以使用 session 来记住用户是否已登录。为此,请添加:
session_start();
在config.php中
在每个需要登录的页面上,将其添加到脚本顶部:
require_once('config.php');
if ($secured && (!isset($_SESSION['loggedin']) || !$_SESSION['loggedin'])) {
header('Location: index.html');
exit;
}
Auth.php 应如下所示。
<?php
require_once("config.php");
If (!$secured) {
header('Location: page1.html');
exit;
}
if (isset($_POST['user']) && isset($_POST['password'])) {
if ($_POST['user']==$username && $_POST['password']==$password) {
// OK
$_SESSION['loggedin'] = true;
header('Location: page1.html');
exit;
} else {
echo "Bad login credentials. <a href=\"index.html\">Try again</a>";
}
} else {
// not logging in
header('Location: index.html');
exit;
}
?>
要注销,只需创建一个脚本 logout.php:
<?php
require_once('config.php');
$_SESSION['loggedin'] = false;
?>
关于php登录脚本中只有一个用户在变量中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6164576/