Version: 1
Type: Full Script
Category: HTTP
License: GNU General Public License
Description: This is the basic code that I have used that allows users to authenticate using HTTP, PHP and simple mysql. This allows you to utilize your database without having to hard code your user/pass in the script or use the .htaccess or another flat/text file.
<? header("Cache-control: private"); // turn off any unwanted errors for the users error_reporting(0); if (isset($PHP_AUTH_USER) && $PHP_AUTH_USER != ''){ // the database information can inserted into another file and // then inserted using the require(); statement // ex) require("db_info.inc"); $database="database"; $username=strtolower($PHP_AUTH_USER); $password=strtolower($PHP_AUTH_PW); if (!mysql_connect(localhost,$username,$password)) { header('WWW-Authenticate: Basic realm="basic"'); header('HTTP/1.0 401 Unauthorized'); echo "Sorry, but you need to enter your <a href='login.php'>login information</a>."; } else { $redirect_to = $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "main.php" ; if( $_SERVER['SERVER_PORT'] == 43 ) // set to secure port # { $server = 'https'; } else { $server = 'http'; } print "<meta http-equiv="refresh" content="0;URL=$server://$redirect_to"> "; //echo "<P>You're authorized!</p>"; // for testing purposes mysql_close(); } } //close the if isset else if (!isset($PHP_AUTH_USER)) { header('WWW-Authenticate: Basic realm="basic"'); header('HTTP/1.0 401 Unauthorized'); echo "Please enter your <a href='login.php'>login information</a>"; exit; } ?>