Oct 2008 29
If you want to secure a web page, but don’t want to have integrate a database and don’t require unique usernames and passwords for each user this solution may work for you!
<?php function passwordProtect($username, $password){ if ( ( !isset($_SERVER['PHP_AUTH_USER']) || ( isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] != $username ) ) && ( !isset($_SERVER['PHP_AUTH_PW']) || ( isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] != $password ) ) ) { header('WWW-Authenticate: Basic realm="Login"'); header('http/1.0 401 Unauthorized'); echo 'Please Login to continue.'; exit; } } ?>
Then to use the code simply echo the function
<?php echo passwordProtect('username', 'password'); ?>







This method can be a problem if you’re not running PHP as a module however. PHP_AUTH_USER and PHP_AUTH_PW are not set when PHP is running as cgi, which is often the case on windows servers. Just something to be aware of.