Skip to main content

HTTP Basic Authentication PHP

HTTP Basic authentication is a way to authenticate where user agent password the user information to server and server authenticates the given user detail and provide further access. While information gets transmitted to the server they are base64 encoded. Its server responsibility to validate the detail. If you are using Apache as a web server you can implement basic auth using .htaccess and htpasswd with the password file. But if you want you can implement HTTP basic authentication with PHP also. In this tutorial, we will explore on HTTP basic authentication PHP. First, we will explore how exactly HTTP authentication works. Once you will have the idea of how it works you can easily write PHP code. So later in the later part of the tutorial, we will cover our real topic i.e. HTTP basic authentication PHP.
HTTP Basic Authentication PHP

What is HTTP basic Authentication and How it works

HTTP basic authentication is a mechanism to validate the user. In HTTP basic authentication browser takes username and password from the user in input box like above image and send back to the server. The server then validates the detail and found it correct then grant the require access of pages to the user. If server found user unauthenticated then again ask the browser to get user detail and then again browser asks the user to input user detail. If the user completely denies entering user detail then server send 401 HTTP code.

Now the question is, how this complex communication happens between server and browser? The answer is via HTTP headers. While in the complete HTTP basic auth process, the server and browser communicate via HTTP header. Below is the step by step process with HTTP header on how server and browser communicate in HTTP basic authentication process:

  1. The User request for the HTTP basic auth protected page via the web browser.
  2. The Server sends the following header to  the browser so that browser can ask the user to enter the password:
    header("WWW-Authenticate: Basic realm=\"Please enter your username and password to proceed further\"");
    header("HTTP/1.0 401 Unauthorized");
  3. User decodes the header sent by the server and understand that the username and password is required. So User open the username password dialog box in front of user. With two button OK and Cancel.
  4. If user will click on “Cancel” which means completly dening to enter the username and passoword then as per the next line of header(please refer step 2) It send HTTP status 401.
  5. If user will enter username and password and click on button “Ok” then Browser sends the username and password to server with header name “Authorization“. Browser always sends the username and password by merging the username and password in string format username:password and encode in base64. For example
    Authorization: sdfwsdfds7d7sd
  6. Now once server receives the authorization header it decodes and validates the user credential. If server found the user credential valid then grant access to further pages by creating session cookie or other approaches. If server found the username password invalid then again send the HTTP header for username and password mentioned in step 2 and complete cycle get repeated.

So complete Basic auth game runs on HTTP headers. For more in-depth knowledge about HTTP Basic Authentication can visit Wikipedia Basic Auth or RFC for HTTP Basic Auth.

Implementation of Basic Authentication With PHP

Implementing Basic Authentication with PHP is very easy if you have the idea of how HTTP basic authentication works. So before coming to the section of how to implement Http basic authentication with PHP please read and understand the previous section very carefully.

Now below thing you need to do to implement the basic auth using PHP script:

  1. Use Header function of PHP and send the required header for basic auth.
  2. Validate the username and password received from basic authentication.

Below is the code for HTTP Basic authentication PHP
header("WWW-Authenticate: Basic realm=\"Please enter your username and password to proceed further\"");
header("HTTP/1.0 401 Unauthorized");
print "Oops! It require login to proceed further. Please enter your login detail\n";
exit;

The first line of code informs browser to show HTTP authentication box to the user and the code execution waits till either user enter the information in Auth box or click on cancel button.

If the user will enter the information and click on “Ok” button request goes to the server to validate the credential, otherwise next line from above code will be executed and which sends HTTP error 401 which is for Unauthorized access and then print the line mentioned.

Below is the code to validate the HTTP basic auth detail in PHP.
if ($_SERVER['PHP_AUTH_USER'] == 'admin' && $_SERVER['PHP_AUTH_PW'] == [email protected]') {
echo 'User validated';
exit;
}

Username and Password is stored in $_SERVER variable $_SERVER[‘PHP_AUTH_USER’] & $_SERVER[‘PHP_AUTH_PW’]. Above code is to validate the username and password hard coded. If you want you can use $_SERVER[‘PHP_AUTH_USER’] & $_SERVER[‘PHP_AUTH_PW’] and validate from your mysql database as well.

Below is the code with complete flow:
<?php
if (!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW'])) {
header("WWW-Authenticate: Basic realm=\"Please enter your username and password to proceed further\"");
header("HTTP/1.0 401 Unauthorized");
print "Oops! It require login to proceed further. Please enter your login detail\n";
exit;
} else {
if ($_SERVER['PHP_AUTH_USER'] == 'admin' && $_SERVER['PHP_AUTH_PW'] == [email protected]') {
echo 'User validated';
exit;
} else {
header("WWW-Authenticate: Basic realm=\"Please enter your username and password to proceed further\"");
header("HTTP/1.0 401 Unauthorized");
print "Oops! It require login to proceed further. Please enter your login detail\n";
exit;
}
}

So above code will first check if the $_SERVER[‘PHP_AUTH_USER’] & $_SERVER[‘PHP_AUTH_PW’] exists or not. If exists then it will try to validate the user. If user get validated print the success message. If user validation failed or if $_SERVER[‘PHP_AUTH_USER’] & $_SERVER[‘PHP_AUTH_PW’] is not exists then in both cases it send header of HTTP basic authentication.

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

Leave a Reply

Your email address will not be published. Required fields are marked *

shares