Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

Authentication

The post will contain different authentication methods. Some day in the future they may be added to class.
/**
* The function provide basic HTTP authentication
* @author Samuil Banti
* @copyright (C) 2018 - Samuil Banti
* @license GNU/GPLv3<a href=" http://www.gnu.org/licenses/gpl-3.0.html" target="_blank"> http://www.gnu.org/licenses/gpl-3.0.html</a> 
* @param array $users - List of allowed users. The keys of the array contain the usernames and the values are the MD5 encripted passwords including salt at the end.
* @param string $salt - The salt used during the passwords encription.
* @param string $message - Custom message in case of authentication failure. If empty a default one will be set.
* @return boolean - True in case of successful authentication.
*/
function http_authenticate($users, $salt = '', $message = false)
{
    if(!$message) {
	$message = 'Authentication falure <a href="'.$_SERVER['REQUEST_URI'].'" >try again</a>';
    }

    if (!isset($_SERVER['PHP_AUTH_USER'])) {
	header('WWW-Authenticate: Basic realm="Sami\'s Auth"');
	header('HTTP/1.0 401 Unauthorized');
	exit($message);
    }
    
    $username = $_SERVER['PHP_AUTH_USER'];
    $password = md5($_SERVER['PHP_AUTH_PW'].$salt);
    
    if (isset($users[$username]) && $users[$username] == $password) {
	return true;
    }
    header('HTTP/1.0 401 Unauthorized');
    exit($message);
}