author: Krasimir Tsonev

Hi there, I'm . Senior front-end engineer with over 13 years of experience. I write, speak and occasionally code stuff. Follow me on Twitter, GitHub, Facebook or LinkedIn

Basic PHP authentication

The .htaccess file is actually a possible solution for this purpose. The problem with this approach is that the value of AuthUserFile should contain an absolute path. It also works with relative paths, but it is relative based on ServerRoot, which in most of the cases is different from DocumentRoot. I also didn't want to deal with sessions or cookies and after a short research I found the answer.

	class Authenticator {
	
		public static $username = "east";
		public static $password = "admin2011";
		
		public function check() {
			if (
				isset($_SERVER['PHP_AUTH_USER']) &&
				isset($_SERVER['PHP_AUTH_PW']) &&
				$_SERVER['PHP_AUTH_USER'] == self::$username &&
				$_SERVER['PHP_AUTH_PW'] == self::$password
			) {
				return true;
			} else {
				header('WWW-Authenticate: Basic realm="Please login."');
				header('HTTP/1.0 401 Unauthorized');
				die("Wrong username or password!");
			}
		}
	
	}
	
And the usage:

	Authenticator::check();
	
The result is similar to the one provided by .htaccess solution. Have in mind that it is possible to have $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] set already. The script above works only under Apache with mod_auth running. However, I think that it is kinda common setup ;)
If you enjoy this post, share it on Twitter, Facebook or LinkedIn. Or maybe comment below: