PHP – Simple authentication script with PHP_AUTH_USER and PHP_AUTH_PW
November 18, 2007
In this howto, we can create a little PHP authentication system with only few rows of PHP code. We can use header() function to submit the “Authentication Required” Message to the client browser, so on client browser we can see a dialog popup that require Username and Password. When we fill the fields, we can receive variables through arrays: “$_SERVER: PHP_AUTH_USER” and “$_SERVER: PHP_AUTH_PW”. We can use this simple authentication system only if PHP runtime is installed as Apache module.
Now we can see how it works through the source code:
<?php
#We have to specify username and password for authentication
$user = “userdemo”;
$pass = “passdemo”;#We ask to open a popup of Authentication System on the client browser
if (!isset($_SERVER['PHP_AUTH_USER']))
{
header(“WWW-Authenticate: Basic realm=\”You must Log In!\”");
Header(“HTTP/1.0 401 Unauthorized”);
exit;
}
#We have to verify is Login User and Password are the same of defined variables
else if (($_SERVER['PHP_AUTH_USER'] == $user) && ($_SERVER['PHP_AUTH_PW'] == $pass))
{
echo “Now you are Logged In”;
}
#If Login not is correct
else
{
echo “Error!”;
}
?>









