Browser Authentication with PHP

Often, I need a quick and dirty way to check passwords on a website. Sometimes, the passwords need to be secure, sometimes they don't.

One easy way to setup authentication is to let Apache do it for you. That involves creating a .htaccess file and creating a password file. But, did you know you can do the same thing directly from PHP?

Here's a simple example of a piece of code that causes the browser to prompt.

<?php

  // Test password
  if ($_SERVER['PHP_AUTH_USER'] == 'joel' and $_SERVER['PHP_AUTH_PW'] == 'joel') {

    // Say hello
    echo 'Hi, Joel!';
	    	
  } else {

    // Ask for password
    header('WWW-Authenticate: Basic realm="HTTP Auth Test"');
		
  }

?>

The password is typically sent “in the clear”, so this shouldn't be used for anything that needs more than the most basic protection. If, however, you require the request via HTTPS, then the data is encrypted and it's perfectly safe.

Having the password directly inside your PHP code can also be a security problem, although it's a fairly common practice. As long as the server is secure and configured so that your PHP file cannot be viewed by others, it should be fine. For a little extra security, I often put my passwords in a config file and locate it outside of the publicly accessible directory. You can also take one step further and encrypt the password before storing it in the config file.

comments powered by Disqus
php/browser_authentication_with_php.txt · Last modified: 2020/06/01 22:53 (external edit)