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

发布于 2024-10-09 01:28:55 字数 1598 浏览 0 评论 0原文

index.php

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

login.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
}
?>

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

  • 如何获取它以便我可以重新加载 index.php 并显示“hello”?
  • 如何让login.php在成功验证后自动加载index.php,以便我可以将其发送到“hello”?
  • 稍后,使用 cookie 存储用户提交的登录数据(这样他们就不必重新填写表单来恢复会话)会有任何潜在的问题吗?

帮助表示赞赏。

index.php

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

login.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:

  • 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?

Help appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

抚笙 2024-10-16 01:28:55

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

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

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

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

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

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

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

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

云淡风轻 2024-10-16 01:28:55

更好的做事方式:
检查 index.php 中的会话变量,如果未设置则重定向。像这样

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

在login.php中,身份验证成功后,重定向到index.php并在那里进行回显。

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() 应该在任何内容回显到浏览器之前出现。

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

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.

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.

╰沐子 2024-10-16 01:28:55

您应该:

  1. 始终尝试调用session_start() 尽早 - “要使用基于 cookie 的会话,必须在向浏览器输出任何内容之前调用 session_start()。”< /em>

  2. 在执行$name = $_POST['name'];之前检查$_POST['name']是否已设置。你可以这样做:

    $name = isset($_POST['name']) ? $_POST['名称'] : '';
    
  3. 用户名直接存储在$_SESSION中,以便cookie仅保存PHPSESSID并且不包含可以替换/滥用的数据最终用户:

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

    header('位置:index.php');
    出口;
    

所以它可能是这样的:

<?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'];
}
?>

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 username directly in $_SESSION so that cookie holds only PHPSESSID and no data that could be replaced / abused by the end users:

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

    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'];
}
?>
遮云壑 2024-10-16 01:28:55

使用它重定向到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('');
}

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

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

然后后来,

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

Use this to redirect to index.php (I hope it answers your #1 and #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:

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

and then later on,

if (isset($_SESSION['user']))
    echo "Hello, " . $_SESSION['user'];
一梦浮鱼 2024-10-16 01:28:55

如何获取它以便重新加载index.php并显示“hello”?

删除 else,这样它将始终显示“hello”:

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

如何让login.php在成功验证后自动加载index.php,以便我可以将其发送到“hello”?

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

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

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

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

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

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"?

Replace echo "Access granted!"; with 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?

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.

淤浪 2024-10-16 01:28:55

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

我通常做的是以用户密码本身作为密钥来加密密码和用户,这样,如果您也以这种方式将他们的凭据存储在您自己的数据库中,则即使站点维护人员也无法解密并窃取它密码。任何数据库转储工具都只有一些元数据。 (您还应该加密用户名...)

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

所以请记住:

  • 检查会话和 cookie 是否存在有效内容(如果存在),
  • 然后在转发到您的身份验证过程之前检查用户和密码输入字段是否有正常数据。
  • 在服务器端加密用户和密码信息,如果您将其发送到客户端,则在客户端加密(cookie?)。
  • 至少使用 AES256(mysql 从 5.6 开始就支持这个本机,它真的很容易使用......)来加密数据。
  • 使用 sha3-256 进行哈希处理。
  • 查看加密和散列指南,因为它很容易搞砸。
  • 请一位知情的朋友尽最大能力测试您的设置,以获得一箱啤酒 ^^ 并与他一起享受乐趣并了解有关您的代码的大量内容:D

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

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.

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...)

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文