如何在 PHP 中创建一个非常简单的用户名 - 密码登录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4516565/
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 13:16:35  来源:igfitidea点击:

How to create a very simple username - password login in PHP?

phpsessionauthenticationloginsession-cookies

提问by Hamster

index.php

索引.php

<?php
if( $_SESSION['auth'] != 1 ) {
    require( 'login.php' );
}
else {
    echo "hello";
}
?>

login.php

登录.php

<?php
$name = $_POST['name'];
$pass = $_POST['pass'];

if( isset($name) || isset($pass) )
{
    if( empty($name) ) {
        die ("ERROR: Please enter username!");
    }
    if( empty($pass) ) {
        die ("ERROR: Please enter password!");
    }


    if( $name == "<some name>" && $pass == "<some password>" )
    {
        // Authentication successful - Set session
        session_start();
        $_SESSION['auth'] = 1;
        setcookie("username", $_POST['name'], time()+(84600*30));
        echo "Access granted!";
    }
    else {
        echo "ERROR: Incorrect username or password!";
    }
}


// If no submission, display login form
else {
?>
    <html>
    <head></head>
    <body>
    <center>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    Username: <input type="text" name="name" value="<?php echo $_COOKIE['username']; ?>">
    <p />
    Password: <input type="password" name="pass">
    <p />
    <input type="submit" name="submit" value="Log In">
    </center>
    </body>
    </html>
<?php
}
?>

So, as I'm still learning PHP, there's a few things I'm trying to figure out now:

所以,由于我还在学习 PHP,我现在想弄清楚一些事情:

  • How do I get it so I can reload index.php and it displays 'hello'?
  • How can I get login.php to auto-load index.php on a successful authentication so I can get it to that "hello"?
  • Later, would using a cookie to store the user's submitted login data (so they don't have to refill the form to restore their session) have any potential problems?
  • 我如何获得它以便我可以重新加载 index.php 并显示“你好”?
  • 我怎样才能让 login.php 在成功的身份验证后自动加载 index.php 以便我可以把它变成“你好”?
  • 之后,使用 cookie 来存储用户提交的登录数据(这样他们就不必重新填写表单来恢复他们的会话)有什么潜在问题吗?

Help appreciated.

帮助表示赞赏。

回答by alexn

1, You're missing session_start() in index.php. Add it and you should be able to see 'Hello world'

1,你在 index.php 中缺少 session_start()。添加它,您应该能够看到“Hello world”

2, Replace your line with "Access granted!" with a redirect:

2,将您的行替换为“已授予访问权限!” 使用重定向:

header('Location: index.php');
exit;

3, You can definitely store credentials in a cookie, but you should always hash and salt the password. Hereis a good article about password hashing.

3、您绝对可以将凭据存储在 cookie 中,但您应该始终对密码进行散列和加盐。是一篇关于密码散列的好文章。

回答by Srisa

Better way of doing things: Check for the session variable in the index.php and redirect if it is not set. Something like this

更好的处理方式:检查 index.php 中的 session 变量,如果未设置则重定向。像这样的东西

session_start();
if (!isset($_SESSION['auth']) || $_SESSION['auth'] != 1) {
   header('Location: login.php');
   exit();
}
echo 'Hello'; 

In the login.php, after successful authentication, redirect to index.php and do the echo there.

在 login.php 中,认证成功后,重定向到 index.php 并在那里做 echo。

session_start();
if( $name == "<some name>" && $pass == "<some password>" )
{
// Authentication successful - Set session
   $_SESSION['auth'] = 1;
   setcookie("username", $_POST['name'], time()+(84600*30));
   header('Location: index.php');
   exit();
}
else {
  echo "ERROR: Incorrect username or password!";
}

session_start() should come before any content is echoed to the browser.

session_start() 应该在任何内容回显到浏览器之前出现。

回答by LihO

You should:

你应该:

  1. always try to call session_start()as early as possible - "To use cookie-based sessions, session_start()must be called before outputing anything to the browser."

  2. check whether $_POST['name']isset before doing $name = $_POST['name'];. You can do:

    $name = isset($_POST['name']) ? $_POST['name'] : '';
    
  3. store the usernamedirectly in $_SESSIONso that cookie holds only PHPSESSIDand no data that could be replaced / abused by the end users:

    $_SESSION['user'] = 'John';
    
  4. try to redirect the user to index.phpto see the immediate result of changing the session:

    header('Location: index.php');
    exit;
    
  1. 始终尝试session_start()尽早调用- “要使用基于 cookie 的会话,session_start()必须在向浏览器输出任何内容之前调用。”

  2. $_POST['name']在做之前检查是否isset $name = $_POST['name'];。你可以做:

    $name = isset($_POST['name']) ? $_POST['name'] : '';
    
  3. username直接存储,$_SESSION以便 cookie 只保存PHPSESSID而没有最终用户可以替换/滥用的数据:

    $_SESSION['user'] = 'John';
    
  4. 尝试将用户重定向index.php到查看更改会话的直接结果:

    header('Location: index.php');
    exit;
    

So this is how it could look like:

所以这就是它的样子:

<?php
session_start();
if (empty($_SESSION['user'])) {

    $name = isset($_POST['name']) ? $_POST['name'] : '';
    $pass = isset($_POST['pass']) ? $_POST['pass'] : '';

    if ($name != '' || $pass != '')
    {
        if ($name === '')
            die("ERROR: Please enter the username!");

        if ($pass === '')
            die("ERROR: Please enter the password!");

        if ($name == "test" && $pass == "test") {

            // authentication successful, save username in session:
            $_SESSION['user'] = 'John';

            // redirect to index.php to welcome the logged in user:
            header('Location: index.php');
            exit;
        }
        else {
            die("ERROR: Incorrect username or password!");
        }
    }

    // no submitted data, display form:
    ?>
        <html>
        <head></head>
        <body>
            <center>
            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
            Username: <input type="text" name="name" value=""><br>
            Password: <input type="password" name="pass"><br>
            <input type="submit" value="Log In">
            </form>
            </center>
        </body>
        </html>
    <?php
}
else {
    // info about current user is stored in session, welcome this user:
    echo "hello " . $_SESSION['user'];
}
?>

回答by The Scrum Meister

How do I get it so I can reload index.php and it displays 'hello'?

我如何获得它以便我可以重新加载 index.php 并显示“你好”?

Remove the else, so it will always display the "hello":

删除else,因此它将始终显示“你好”:

if($_SESSION['auth'] != 1) {
    require('login.php');
}
// Either way always print.
echo "hello";

How can I get login.php to auto-load index.php on a successful authentication so I can get it to that "hello"?

我怎样才能让 login.php 在成功的身份验证后自动加载 index.php 以便我可以把它变成“你好”?

Replace echo "Access granted!";with header('Location:index.php');

替换echo "Access granted!";header('Location:index.php');

Later, would using a cookie to store the user's submitted login data (so they don't have to refill the form to restore their session) have any potential problems?

之后,使用 cookie 来存储用户提交的登录数据(这样他们就不必重新填写表单来恢复他们的会话)有什么潜在问题吗?

As long as are using this as a way to autofill the username only. and require the users to enter their password every time. otherwise a user can set his username cookie to "admin" or some other user.

只要使用它作为仅自动填充用户名的方式。并要求用户每次输入密码。否则,用户可以将他的用户名 cookie 设置为“admin”或其他用户。

回答by UltraInstinct

Use this to redirect to index.php (I hope it answers your #1 and #2)

使用它重定向到 index.php(我希望它回答你的 #1 和 #2)

if( $name == "<some name>" && $pass == "<some password>" )
{
    // Authentication successful - Set session
    session_start();
    $_SESSION['auth'] = 1;
    setcookie("username", $_POST['name'], time()+(84600*30));
    //echo "Access granted!";
    header("Location: index.php");
    die('');
}

You are using cookies to store the username directly. That is not a great option. What if a user modifies the cookies, to read some other username? Instead use $_SESSION['..']Like this:

您正在使用 cookie 直接存储用户名。这不是一个很好的选择。如果用户修改 cookie 以读取其他用户名怎么办?而是使用$_SESSION['..']像这样:

$_SESSION['user']=$_POST['name'];

and then later on,

然后后来,

if (isset($_SESSION['user']))
    echo "Hello, " . $_SESSION['user'];

回答by Ringnull

no one is mentioning that you should check that the session is actually a valid one... if you just check it's set you can most likley fake it and get through. also to hash credentials into the cookie i would encrypt it first server side and then hash it. just in case somewhere in the future someone breaks the hash type. sha3-256 is your best choice here as it's not known to be broken and should resist alot of computing power increase in the future.

没有人提到你应该检查会话实际上是一个有效的......如果你只是检查它的设置,你最有可能伪造它并通过。还要将凭据散列到 cookie 中,我会先加密它,然后在服务器端对其进行散列。以防万一将来有人打破散列类型。sha3-256 是您最好的选择,因为它不会被破坏,并且应该可以抵抗未来的大量计算能力增长。

What i usually do is to encrypt password and user with the user password itself as key, that way, if you also store their credentials in this fasion in your own database, there is no way even for the site maintainer to decrypt it and steal the passwords. and any db dumping skiddie will have only some meta data. (you should also encrypt the usernames...)

我通常做的是用用户密码本身作为密钥来加密密码和用户,这样,如果您还将他们的凭据存储在您自己的数据库中,那么站点维护者也无法解密并窃取密码。并且任何 db dumping skiddie 都只有一些元数据。(您还应该加密用户名...)

It seems a little conveluted to be a 'simple login and password for the users' but really as simple as possible should still consider security for your users, even if it's not a public site...

“用户的简单登录名和密码”似乎有点令人费解,但实际上尽可能简单仍应考虑用户的安全性,即使它不是公共站点...

So remember:

所以请记住:

  • check sessions and cookies for valid contents if they are there
  • check user and pw input fields for sane data before forwarding to your auth process.
  • encrypt user and pw information in your server side, and in the client side if you send it there (cookies?).
  • use AES256 atleast (mysql support this native since 5.6 its really easy to use...) for encrypting data.
  • use sha3-256 for hashing.
  • look at guides for crypto and hashing as it's easy to mess up.
  • ask a friend in the know to test your setup to best of their ability for a crate of beer ^^ and have fun with him and learn a bunch of stuff about your code :D

    • lastly, i will have forgotten (or don't know atall) alot of stuff, so there will be missing bullets! :D
  • 检查会话和 cookie 是否存在有效内容
  • 在转发到您的身份验证过程之前,请检查用户和密码输入字段是否有合理的数据。
  • 在您的服务器端加密用户和密码信息,如果您将它发送到客户端(cookies?),则在客户端加密。
  • 至少使用 AES256(mysql 从 5.6 开始支持这个本机它真的很容易使用......)来加密数据。
  • 使用 sha3-256 进行散列。
  • 查看加密和散列指南,因为它很容易搞砸。
  • 请一位知情的朋友来测试您的设置,以尽其所能为一箱啤酒 ^^ 并与他一起玩乐并学习有关您的代码的大量内容:D

    • 最后,我会忘记(或根本不知道)很多东西,所以会丢失子弹!:D