PHP Authenticate

Sheeraz Gul Feb 15, 2024
  1. Use Basic HTTP Authentication in PHP to Authenticate the User
  2. Use Digest HTTP Authentication in PHP to Authenticate the User
PHP Authenticate

HTTP authentication sends special HTTP headers to the client and asks for authentication codes to access the page.

It is a PHP built-in way to validate users for particular tasks. PHP has two HTTP authentication methods, Basic and Digest.

The HTTP authentication will generate a pop-up to ask for authentication information.

It uses the array $_SERVER variables, PHP_AUTH_USER and PHP_AUTH_PW to authenticate the user and AUTH_TYPE to set the authentication type.

Use Basic HTTP Authentication in PHP to Authenticate the User

The basic HTTP authentication uses non-encrypted PHP base64 encoding; that is why it should only be used when security like HTTPS is provided.

These securities are called transport layer securities.

<?php

if( ( isset($_SERVER['PHP_AUTH_USER'] ) && ( $_SERVER['PHP_AUTH_USER'] == "admin" ) ) AND ( isset($_SERVER['PHP_AUTH_PW'] ) && ( $_SERVER['PHP_AUTH_PW'] == "password" )) )

{

    echo(" Hello ".$_SERVER['PHP_AUTH_USER']."! <br>\n");

}
else
{
    // These headers will cause the browser to ask for authentication information
    header('WWW-Authenticate: Basic realm="This page is only authorized to registered users"');
    header('HTTP/1.0 401 Unauthorized');

    //This text will be shown after several failed attempts, or you cancel the pop-up box.
    echo"Protected by HTTP Authentication <br>";
	echo "Use <b>admin</b> for the username, and <b>password</b> for the password to enter";
    }
?>

This code will generate a pop-up box and ask for the username and password.

If you put the correct information, you will get access to the page, and if it is wrong, the code will redirect back a few times and finally print a failed message.

The username is admin, and the password is password.

Output:

PHP Function Alert Message

If the information is correct:
"Hello admin!" 
If the information is failed:
"Protected by HTTP Authentication"
"Use admin for the username, and password for the password to enter."

Use Digest HTTP Authentication in PHP to Authenticate the User

The digest authentication uses encryption by using a hash function on the information.

This information includes the user info, the HTTP method, the server-supplied nonce value, and the requested URL; it is more secure than basic HTTP authentication because the information is encrypted.

// User authentication info
$auth_info = array('user1' => 'pass1', 'user2' => 'pass2');

// First of all check PHP_AUTH_DIGEST variable, if it is empty the header will redirect the page to pop up box.
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('WWW-Authenticate: Digest realm="Restricted area",qop="auth",nonce="'.uniqid().'",opaque="'.md5("Restricted area"));
    header('HTTP/1.1 401 Unauthorized');

    exit('You cancelled the authentication');
}

// it is required to check the Digest Authentication Variable first before converting the information to md5

if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($auth_info[$data['username']])){
    exit('The authentication information entered is not correct!');
}

// generating the valid authentication response using the client info and server request method

$auth_hash1 = md5($data['username'] . ':Restricted area:' . $auth_info[$data['username']]);
$auth_hash2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$auth_response = md5($auth_hash1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$auth_hash2);

if ($data['response'] != $auth_response){
    exit('The authentication information entered is not correct!');
}
else{
// if authentication response matches the info 
    echo 'Welcome ' . $data['username'].' you are an authenticated user';
}

// The function below is from the official PHP manual, https://www.php.net/manual/en/features.http-auth.php. It is used to parse the HTTP digest.
function http_digest_parse($txt)
{
    
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}

The code above shows the process of applying the digest HTTP authentication method. You can use http_digest_parse() function from PHP manual and use it to parse the HTTP Digest Authentication.

The output will be similar to basic, but it is more secure. There are two users, user1 and user2.

There are two passwords, pass1 and pass2, respectively. You can put any information and log in.

Output:

PHP Function Alert Message

If the information is correct:
"Welcome admin you are an authenticated user"
If the information is failed:
"The authentication information entered is not correct!"
If you cancel the pop up:
"You cancelled the authentication"
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook