PHP Authentication (beginner)

别等时光非礼了梦想. 提交于 2019-12-11 04:06:25

问题


I have recently started learning PHP. I made a basic website and wanted to basically password it. I'd appreciate it if someone could tell me why this doesn't work. I know it doesn't work because I've tried it; I just don't understand why.

<?php
$user='user';
$pass='pass';

header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm='.'hello');
if($_SERVER['PHP_AUTH_USER']==$user && $_SERVER['PHP_AUTH_PW']==$pass)
    echo 'Authorized';
else
    exit('Exiting');
?>
...
REST OF WEBSITE
...

I know the 'correct' way of doing it is like this:

<?php
if(!isset($_SERVER['PHP_AUTH_USER']))
{
     header('HTTP/1.1 401 Unauthorized');
     header('WWW-Authenticate: Basic realm='.'hello');
     exit('Exiting');
}
else
{
    $user='user';
    $pass='pass';
    if($_SERVER['PHP_AUTH_USER']==$user && $_SERVER['PHP_AUTH_PW']==$pass)
        echo 'Authorized';
    else
    {
        header('HTTP/1.1 401 Unauthorized');
        header('WWW-Authenticate: Basic realm='.'hello');
        exit('Exiting');
    }
}
?>
REST OF WEBSITE

I'd appreciate it if someone could at least point me in the right direction.


回答1:


When using HTTP authentication, your script is run twice: the first time, $_SERVER['PHP_AUTH_USER'] is unset, and you have to tell the browser that the page needs authentication. Then the browser reloads the page, though this time $_SERVER['PHP_AUTH_USER'] contains the username and $_SERVER['PHP_AUTH_PW'] the password that the user has provided. If this matches the correct credentials ($user and $pass), you would go on to send the page to the browser.

Your code does not differentiate these two cases, and thus it will tell the browser that it requires a username and password, even when the correct credentials already have been sent.




回答2:


Using this line:

header('HTTP/1.1 401 Unauthorized');

will tell the browser, that the request failed. As you use it for every request, every request fails.

That's why in the second example it is not always executed but only conditionally.

I created a little demo example. Your browsers login box will be displayed, you can enter anything you like then press cancel if you want to prevent displaying the login-box any longer.

You will then see which data is provided to the PHP script.



来源:https://stackoverflow.com/questions/8770885/php-authentication-beginner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!