PHP


Tips and Tricks of PHP
By Junaid Shabbir
22-Jun-08
Views: 13479

Tips and Tricks of PHP
 
Browser authentication using PHP (Page 7 of 7)
PHP has the ability to show an authentication dialog on the client side by sending an HTTP header to the browser. The syntax to show authentication dialog is given below
header('WWW-Authenticate: Basic realm="Member Area"');
realm is the name of domain or group of pages. If you specify the same realm again, the browser will automatically fill the username field for the user.



The complete code to show authentication dialog is shown below
<?php
	if($_SERVER['PHP_AUTH_USER']!='admin' || $_SERVER['PHP_AUTH_PW']!='admin') {

		header('WWW-Authenticate: Basic realm="Member Area"');
		header("HTTP/1.0 401 Unauthorized");
		die("Please login with a valid username and password.");

	}else {
		$msg="Welcome to Member Area";
	}
?>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>HTTP Authentication</title>
</head>
 
<body>
	<h1><?=$msg?></h1>
</body>

</html>
 
The above code will tell the browser to show an authentication dialog. If the user doesn't provide valid username and password, the dialog will appear again. If the user cancels the dialog the appropriate message will be printed.
Comments
Ethan
[29-Aug-2009]
#1

Just thought i'd say you might want to be sure to validate and clean all data before you output it back to the page for saving form data on a unsuccessful attempt by a user.

Leave a Comment
Age (Required, will not be shown)
Name
Email (Required, will not be shown)
Website (Optional, starting with http://)
 
Are you human ?

Enter the code shown above