Have ever been thorough cpanel ? when you open the link of cpanel, you can see a pop up which ask for entering user name and password for login. Well in my article I’m going to show you how you can build the same kind of page protecting mechanism using http authentication in PHP.
Somebody might say that I can also protect the page by making a login page to access the protected page. Well dude!! you are right, you can do that but the main benefits of this method is “you don’t have to create the login page at all”.
Let’s Start, First of all store the user name and password in the variables
For better security, please store these values in database and authenticate from database.
Now let’s create the http authentication function called authenticate() using header() function available in PHP.
header(‘WWW-Authenticate: Basic realm=”Enter Your Login detail to add money”‘);
header(‘HTTP/1.0 401 Unauthorized’);
echo “You must enter a valid login ID and password to access this resource\n”;
The first line of the function tell browser to open the pop up box to enter user name and password the “realm” element contains the string to be displayed in the pop up box.
And the other two lines are called only when user hits the cancel button of the pop up.
Now let’s start the code of authentication.
if ($_SERVER[‘PHP_AUTH_USER’]==$auth_user && $_SERVER[‘PHP_AUTH_PW’]==$auth_pwd && $_SESSION[‘authorized’]==1)
echo “Your are logged in”;
As you can see in the if statement there are two variables $_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PW’], these are the two values which comes from the user name and password field of pop up and these two are the predefined variables of PHP.
I’ve also used the $_SESSION variable to ensure that the pop up box is displayed at least once in the page since the the else condition is executed first when the page is loaded.
Thats’a all dude, now your page is protected with user name and password but without need to built a login page.
Click here to download the full source code.