Using HTTP authentication with PHP

This topic is intended for advanced users who are familiar with PHP's HTTP authentication functions, and who want to password protect a PHP file, then find out the username and password that the visitor provided so they can be used in the PHP script.

PHP’s HTTP authentication with PHP page explains the concept of this, but doesn’t mention a crucial issue: The plaintext password variables are not normally provided to PHP scripts for security reasons.

You can easily change this. Create a .htaccess file in the same directory as your PHP script and add this single line:

CGIPassAuth On

This tells the Apache Web server to pass the encrypted username and password to PHP (or any other script) in a variable named HTTP_AUTHORIZATION (the documentation for CGIPassAuth explains more about how it works).

PHP will then extract a plaintext version of HTTP_AUTHORIZATION to the PHP_AUTH_USER and PHP_AUTH_PW variables. For example, if you use CGIPassAuth On and view a password-protected directory with username “user” and password “password”, phpinfo() will include this in the variables section:

$_SERVER['PHP_AUTH_PW']: password

Scripts can check these variables to find the username and password.

Should I use a RewriteRule line instead of CGIPassAuth?

The Apache CGIPassAuth command is merely a more modern version of these .htaccess lines that you may see recommended elsewhere:

RewriteEngine on
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]

Either method should give the same results.