Unit 5 Authentication
Unit 5 Authentication
Here, we create a PHP function authenticate(), that contains two sets of username and
password in a PHP array. This function accepts the entered username and password as
parameters of the user and matches them with the credentials stored in an array. If both
username and password match with the stored credentials, then returns TRUE, means the
user can access the web page content, otherwise it returns FALSE and again asks for
credentials.
<?php
function authenticate($user, $pass) {
$users = array('rocky' => '@12etp',
'mufasa' => 'Y1907JL');
if (isset($users[$user]) && ($users[$user] === $pass)) {
return true;
} else {
return false;
}
}
?>
Next, we create a condition that checks whether or not the authentication failed. It sets the
HTTP response header to 401 and asks for the credential again.
if (! authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
http_response_code(401);
header('WWW-Authenticate: Basic realm="Website"');
echo "Please enter a valid username and password.";
exit;
}
In the above code, the HTTP WWW-Authenticate response header defines the
authentication method that should be used to gain access to a resource. Here, it is sent along
with a 401 unauthorized response. When the browser sees the 401 header, it again pops up a
dialog box for username and password. The 'realm' is a security policy domain defined for a
web. It may contain any value to identify a secure area. The value in it will be displayed in
the dialog box.
Complete Code: Basic HTTP Authentication using PHP
<?php
function authenticate($user, $pass) {
$users = array('rocky' => '@12etp',
'mufasa' => 'Y1907JL');
if (isset($users[$user]) && ($users[$user] === $pass)) {
return true;
} else {
return false;
}
}
if (! authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
http_response_code(401);
header('WWW-Authenticate: Basic realm="Please Login"');
echo "Please enter a valid username and password.";
exit;
}
echo 'Welcome to this website';
?>
So, this is how we can secure our web page using simple, basic HTTP authentication. We can
also secure login forms, some important messages and much more using this.
<?php
$password = 'Password'; // Store the string into variable
// Use password_hash() function to create a password hash
$hash_default_salt = password_hash($password, PASSWORD_DEFAULT);
$hash_variable_salt = password_hash($password, PASSWORD_DEFAULT, array('cost' =>
9));
// Use password_verify() function to verify the password matches
echo password_verify('Password', $hash_default_salt ) . "<br>";
echo password_verify('Password', $hash_variable_salt ) . "<br>";
echo password_verify('Password123', $hash_default_salt );
?>
Output:
1
1
0
In this example, the password_verify() method is used to compare the hash created with the
string entered as a parameter. It takes the hash and the string to be compared as parameters
and return true if the password is correct else it returns false.