Getting basic-auth username in php
At my clients hoster $_SERVER['PHP_AUTH_USER']
and $_SERVER["HTTP_AUTHORIZATION"]
were empty but $_SERVER["REMOTE_USER"]
was set!
if ($_SERVER["REMOTE_USER"] == "admin")
echo "Welcome, admin!";
else
echo "Access denied";
Check what you have in $_SERVER (print_r($_SERVER)), sometimes $_SERVER['PHP_AUTH_USER'] is not available.
If you have value for $_SERVER["HTTP_AUTHORIZATION"], you may use:
if (isset($_SERVER["HTTP_AUTHORIZATION"]) {
$auth = $_SERVER["HTTP_AUTHORIZATION"];
$auth_array = explode(" ", $auth);
$un_pw = explode(":", base64_decode($auth_array[1]));
$un = $un_pw[0];
$pw = $un_pw[1];
}
(copied from https://www.codepunker.com/blog/php-a-primer-on-the-basic-authorization-header)
It would seem that the location depends on the server in use:
$_SERVER["REMOTE_USER"]
- CGI standard$_SERVER["PHP_AUTH_USER"]
- APACHE$_SERVER["AUTH_USER"]
- IIS
Simply access this variable:
$_SERVER['PHP_AUTH_USER']