php登录脚本中只有一个用户在变量中设置

标签 php authentication

我正在寻找一个 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/

相关文章:

java - Play 框架 - 具有 session 身份验证的代理请求

php - 您如何在应用程序中定义路径?

php - session 不应自行过期

php - 什么 PHP 需要与 gettext 一起使用?

c# - 创建登录屏幕,WPF,如何存储用户名和密码

javascript - Google 使用 Ember.js 登录

php - Drupal 8 未安装 MAMP Pro 和 Windows 10

php - 在 PHP/MySQL 中更新关系数据库

ios - Swift Firebase 身份验证错误

c# - 使用基于声明的身份验证使用 SharePoint 2010 对同一 AD 进行身份验证时区分 Windows Auth 和 Forms Auth 用户