“401 Authorization Required” with PHP

Posted on Jun 15, 2008 in PHP | 5 comments


Very simple bit of PHP to add to the top of your script if you want to password protect something. I wouldn’t reccommend this for larger bits of software, but if you have a simple script or page that you don’t want people to access, try the following:

$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];
if ($user != 'username' or $pass != 'password'){
	header('WWW-Authenticate: Basic realm="Some text"');
	header('HTTP/1.0 401 Unauthorised');
	die('UNAUTHORISED ACCESS');
}

To change the required passwords, change ‘username’ and ‘password’ on line 4 to your desired credentials (remember to leave the ‘ quotes, just replace the text).

To change the window message that appears when asking for the login credentials, replace the text Some text on line 5 with whatever you want.

If you want a different message to appear in the event of a failed login, change UNAUTHORISED ACCESS. You can even change what happens in a failed login, but always remember to use die() or exit() at this point, otherwise the page will still display.