使用 cookie 进行简单的 PHP 登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4329806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:41:40  来源:igfitidea点击:

Simple PHP login with cookie

php

提问by Cameron

I have begun developing this very simple PHP login that asks for a password to allow access to a website. It also creates a cookie to allow continued access until the user closes their browser window.

我已经开始开发这个非常简单的 PHP 登录,它要求输入密码才能访问网站。它还创建一个 cookie 以允许继续访问,直到用户关闭浏览器窗口。

At the top of each page I check for the cookie:

在每个页面的顶部,我检查 cookie:

<?php

    if(!isset($_COOKIE['authorised']) || ($_COOKIE['authorised'] != 'true'))
    {
        include('login.php'); exit;
    }

?>

If they don't then I exit and show a login form:

如果他们没有,那么我退出并显示一个登录表单:

<?php

    function pageURL()
    {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on")
        {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } 
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    $pageRedirect = pageURL();

    if(isset($_POST['password']) && ($_POST['password'] == 'qwe123'))
    {
        setcookie('authorised', 'true'); header("Location:$pageRedirect",303);
    }
    else
    {
        include('noaccess.php'); exit;
    }

?>
<form action="<?php echo pageURL(); ?>" method="post">
<input type="password" name="password" />
                <input type="submit" title="I agree" value="I agree" name="submit" />
            </form>

The current PHP is from an old Warning page when you had to agree to access the site, I want to modify it to work with a simple form so that if the user types a password say for example 'qwe123' then they create the cookie and then are redirected back to the page but now have access because of the cookie. If they get it wrong then another page is included and exited.

当前的 PHP 来自旧的警告页面,当您必须同意访问该站点时,我想修改它以使用简单的表单,以便如果用户输入密码,例如“qwe123”,则他们创建 cookie 和然后被重定向回页面,但由于 cookie 现在可以访问。如果他们弄错了,则包含另一个页面并退出。

Can someone help me with this? Thanks

有人可以帮我弄这个吗?谢谢

回答by El Yobo

Please don't try to store things like "authenticated" in a client side cookie; that's incredibly insecure. A user can modify anything in a cookie - so in this case, I could look up the cookie in my browser settings and then edit it to set "authenticated" to true. I would then be logged in, without a username or password.

请不要尝试在客户端 cookie 中存储诸如“已验证”之类的内容;这是令人难以置信的不安全。用户可以修改 cookie 中的任何内容 - 因此在这种情况下,我可以在浏览器设置中查找 cookie,然后对其进行编辑以将“已验证”设置为 true。然后我将登录,没有用户名或密码。

Have a look at PHP's session managementfunctions. You should create a session and store any secure information server side, not client side.

看看PHP 的会话管理功能。您应该创建一个会话并存储任何安全信息服务器端,而不是客户端。

An example using sessions would be the following;

使用会话的示例如下;

<?php
session_start();

$secretpassword = 'qwert1234';
$secretusername = 'foobar';

if ($_SESSION['authenticated'] == true) {
   // Go somewhere secure
   header('Location: secure.php');
} else {
   $error = null;
   if (!empty($_POST)) {
       $username = empty($_POST['username']) ? null : $_POST['username'];
       $password = empty($_POST['password']) ? null : $_POST['password'];

       if ($username == $secretusername && $password == $secretpassword) {
           $_SESSION['authenticated'] = true;
           // Redirect to your secure location
           header('Location: secure.php');
           return;
       } else {
           $error = 'Incorrect username or password';
       }
   }
   // Create a login form or something
   echo $error;
   ?>
<form action="login.php"><input type="text" name="username" /><input type="text" name="password" /><input type="submit" value="login" /></form>
<?php
}

It's a pretty ugly example, but this covers the meat of it

这是一个非常丑陋的例子,但这涵盖了它的实质

  • if the user is logged in already, do the secure stuff (of course, the secure.php script should also verify that the user is logged in)
  • if the user is not logged in, but they have submitted a form, check their details
    • if username/password incorrect, set an error messagee
    • if username/password correct, send them to secure place
  • display the error message, if set
  • display a login form
  • 如果用户已登录,请执行安全操作(当然,secure.php 脚本还应验证用户是否已登录)
  • 如果用户未登录,但已提交表单,请检查其详细信息
    • 如果用户名/密码不正确,设置错误信息e
    • 如果用户名/密码正确,将它们发送到安全的地方
  • 显示错误消息(如果设置)
  • 显示登录表单

You run session_start() before sending any other output; this stores a session cookie on the client side, which only stores an identification number on the client side. All other data is stored on the server side, so it cannot be modified by the user.

在发送任何其他输出之前运行 session_start();这在客户端存储了一个会话 cookie,它只在客户端存储一个标识号。所有其他数据都存储在服务器端,因此用户无法修改。

There are several parameters that you can set on this to improve security, including httponly (prevents the cookie from being accessed via javascript, helps against XSS attacks) and secure (only transfer the cookie over SSL). These should be enabled if possible.

您可以为此设置多个参数以提高安全性,包括 httponly(防止通过 javascript 访问 cookie,有助于抵御 XSS 攻击)和安全(仅通过 SSL 传输 cookie)。如果可能,应该启用这些。

回答by helloandre

Just have the form submit to the page where you check the password, and it should work just fine.

只需将表单提交到您检查密码的页面,它应该可以正常工作。

However, you might have to change the $_SERVER["REQUEST_URI"];to a more specific page, as this will simply be the page you are currently at (the page the form submitted to).

但是,您可能需要将 更改$_SERVER["REQUEST_URI"];为更具体的页面,因为这只是您当前所在的页面(提交表单的页面)。