Your PHP Solutions Resource 

Authenticate username and password to individual PHP pages using 401 header

Want to be able to have users authenticate to individual pages, or even have a directory full of pages and only certain pages have authentication? It's as simple as saving the below code into something like "auth.php" and including it into the top of your page you want authenticated protection for.

Just edit the array in the below code with the usernames and passwords for each of your users. Then on the page you want to protect, put this line above any other code.


Or whatever filename you chose for the below code.

Please note that this works in PHP 5.0.1 and higher.

Click here to see it in action.

See source code below for username and password.


//An array containing the username and password separated by comma.
//The below shows three user accounts; user1, user2, and anotheruser.
//NOTE: The last element does not have a comma after it.
$authAccounts = array("user1,password1",

header('WWW-Authenticate: Basic realm="Private"');
header('HTTP/1.0 401 Unauthorized'); 
"Access Denied! You need a valid username and password to access this page.\n";

//If it's the first page load, then we send them right to the authenticate() function
if ((!isset($_SERVER['PHP_AUTH_USER'])) || (!isset($_SERVER['PHP_AUTH_PW'])))

//They've typed in a username and password, let's see how they did
elseif ((isset($_SERVER['PHP_AUTH_USER'])) && (isset($_SERVER['PHP_AUTH_PW'])))
$authAccounts as $account)
    if (
$account == $_SERVER['PHP_AUTH_USER'] . "," $_SERVER['PHP_AUTH_PW'])
$authenticated "TRUE";
  if (
$authenticated != "TRUE")


Copyright 2015
All rights reserved.
Powered by PHP   Powered by PSPad   Powered by MySQL   Last Modified
May 15, 2012 @ 12:51