postimg
Oct 2008 29

Simple PHP HTTP Authentication Page Protection1

Posted In PHP By Tony Virelli

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'); ?>
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • email
  • LinkedIn
  • MySpace
  • PDF
  • Reddit
  • RSS
  • Slashdot
  • StumbleUpon
  • Technorati
  • Twitter

1 comment

  1. Jim Mayes says:

    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.

Leave a comment

Get Adobe Flash playerPlugin by wpburn.com wordpress themes