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. Next section is the step by step process with HTTP header on how server and browser communicate in HTTP basic authentication process.

Steps in Browser and Server in Basic Auth

  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 understands that the username and password are required. So User Browser opens the username password dialog box in front of the user. With two buttons OK and Cancel.
  4. If the user will click on “Cancel” which means completely denied to enter the username and password then as per the next line of the header(please refer step 2) It sends HTTP status 401.
  5. If the user will enter username and password and click on the button “Ok” then Browser sends the username and password to the 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 gets 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 things 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. For detail on $_SERVER you can refer to $_SERVER PHP.

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.

Apache mod_cgi and PHP Basic Auth issue

If you are running PHP as mod_cgi with your apache then you will not get the authentication information in your PHP script, this is because apache does not pass authetication information to your script. Hence you will not get $_SERVER[‘PHP_AUTH_USER’] and$_SERVER[‘PHP_AUTH_PW’]  variable in your PHP script. To get  $_SERVER[‘PHP_AUTH_USER’] and$_SERVER[‘PHP_AUTH_PW’] variable in your script you need to compile Apache with SECURITY_HOLE_PASS_AUTHORIZATION.

Compiling the Apache in your production environment a big deal. So alternatively you can access the basic auth variable in your PHP script using below approach.

Add below code into your .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>

And where you want to access the username and password put following script into your PHP code:

list($username, $password) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

Curl on Basic Auth Page in PHP

If you want to POST data or fetch the webpage using curl script, and the page has the basic auth then in the curl script your need to pass basic auth information into header using curl option CURLOPT_USERPWD

For example:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($curl);
curl_close($curl);

 

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 comment/Ask Question

shares