HTTP Auth无法正常工作

时间:2018-02-22 04:05:09

标签: php http

我传递的用户名和密码如http://user:pass@localhost/try

在我的index.php中我有这段代码。

    $username = null;
    $password = null;


    if (isset($_SERVER['PHP_AUTH_USER'])) {
        $username = $_SERVER['PHP_AUTH_USER'];
        $password = $_SERVER['PHP_AUTH_PW'];

    } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {

            if (strpos(strtolower($_SERVER['HTTP_AUTHORIZATION']),'basic')===0)
              list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

    }

    if (is_null($username)) {

        header('WWW-Authenticate: Basic realm="My Realm"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Text to send if user hits Cancel button';

        die();

    } else {
        echo "<p>Hello {$username}.</p>";
        echo "<p>You entered {$password} as your password.</p>";
    }

但它总是转到is_null($username)

谁能告诉我我做错了什么。 感谢。

1 个答案:

答案 0 :(得分:0)

} elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {

        if (strpos(strtolower($_SERVER['HTTP_AUTHORIZATION']),'basic')===0)
          list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

}

应该是

} elseif (isset($_SERVER['Authorization'])) {

        if (strpos(strtolower($_SERVER['Authorization']),'basic')===0)
          list($username,$password) = explode(':',base64_decode(substr($_SERVER['Authorization'], 6)));

}

参考:https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#Basic_authentication_scheme