September 08, 2011

HTTP authentication via PHP

Here's a small snippet that let's you implement htaccess style http authentication in your PHP scripts. Just define user and password and you are ready to go !

<?php
$user = "myuser";
$pass = "mypass";
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER']!=$user || $_SERVER['PHP_AUTH_PW']!=$pass){
    header('WWW-Authenticate: Basic realm="Enter password to access this page."');
    header('HTTP/1.0 401 Unauthorized');
	echo"You must be logged in";
    exit;
}
# Your protected contents go here !!
?>

Make sure that this code block is present in topmost of your scripts or it'll give errors and authentication will be messed up.

No comments:

Post a Comment