I've been working on this site that is supposed to use HTTP Basic Authentication with htpasswd. The authentication itself works like a charm but sometimes (not always) $_SERVER['PHP_AUTH_USER'] is empty.
I got the recommendation to use REMOTE_USER instead, which also only works from time to time. I'm using PHP as a CGI plugin for Apache, anything else is out of the question, unfortunately. The site is served SSL encrypted over HTTPS.
Why is this happening?
I don't have an exact solution but several ideas that might help you.
$user = !empty($_SERVER['PHP_AUTH_USER'])
? $_SERVER['PHP_AUTH_USER']
: $_SERVER['REMOTE_USER'];
...is a good start. Keep in mind that if you are not using Basic Realm Authentication
, you have to play arround with Digest Realm Authentication
$_SERVER['PHP_AUTH_DIGEST']
.
You should first take care that your variables don't get overriden and checked at the right spot. It might also be possible that the username is empty if simply, someone didn't enter one.
If the authentication was not successfull, you should ensure to send the Connection: close
header.
Now to debug the phenomen, you should write into a log file or send a mail to yourself containing the following text to further investigate:
// variables from http://php.net/manual/en/language.variables.superglobals.php
$log = var_export(array($_SERVER, $_REQUEST, $_COOKIES, $_SESSION), true);
I've also read that in combination with cgi there are other variables set containing the username, take a look into this question/answer: https://stackoverflow.com/a/7792912/1948292
Other variables that may contain user information (taken from the answer above):
$_SERVER['REDIRECT_HTTP_AUTHORIZATION']
$_SERVER['REDIRECT_REMOTE_USER']