Apache HTTP Authentication with PHP

Apache HTTP Authentication with PHP

Apache HTTP Authentication with PHP
=============================

The most common way to set up an HTTP Authentication scheme is using an Apache “htaccess� file

The most common way to set up an HTTP Authentication scheme is using an Apache “htaccess� file
using this you like to determine whether to accept or deny access to a Web site.
When installed as an Apache module, PHP provides two special global variables: $PHP_AUTH_USER and

$PHP_AUTH_PW. These contain the username and password that accompanied the current HTTP request, respectively. Using PHP’s

header() function, you can then respond with an HTTP 401 error when the username, password, or both are incorrect.

For Example:
========
page that may only be viewed if the user enters username “admin� and password “pass�:

<?php
if ($PHP_AUTH_USER != “admin�
or $PHP_AUTH_PW != “pass�):
// wrong username/password.
// Send HTTP 401 error to make the
// browser prompt the user.
header(”WWW-Authenticate: ” .
“Basic realm=\â€?Protected Page: ” .
“Enter your username and password ” .
“for access.\â€?â€?);
header(“HTTP/1.0 401 Unauthorized�);
// Display message if user cancels dialog
?>
<HTML>
<HEAD><TITLE>Authorization Failed</TITLE></HEAD>
<BODY>
<H1>Authorization Failed</H1>
<P>Without a valid username and password,
access to this page cannot be granted.
Please click ‘reload’ and enter a
username and password when prompted.
</P>
</BODY>
</HTML>
<?php else: ?>
…page contents here…
<?php endif; ?>

As you can see, checking the username and password entered is as simple as checking the variables $PHP_AUTH_USER and

$PHP_AUTH_PW. When an incorrect user/pass combination is detected, you respond with two HTTP headers

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.