To authenticate a user includes the following steps:
- Identifying visitors
- Implementing access control
- Authentication
Identifying Visitors
The web is fairly anonymous medium, but it is often useful to know who is visiting your site to focus on right business area. You are able to get little about the visitors due to users privacy. With a little work server can find out quite lot about users computers, networks, browsers, etc. From visitor’s IP address you are able to know visitor’s geographic location.
Implementing access control
Simple access control is not difficult to implement. A simple PHP script is shown below.
<?php
//create short names for variables
$name = $HTTP_POST_VARS['name'];
$password = $HTTP_POST_VARS['password'];
if(empty($name) || empty($password)){
//Visitor needs to enter a name and passwor.
?>
<strong>Please Log In</strong>
<form method=”post” action=”login.php”>
<label>User Name: </label> <input type=”text” name=”name” />
<label>Password:</label> <input type=”password” name=”password” />
<input type=”submit” value=”Log In” />
</form>
<?php
}
else if($name==’user’&& $password==’pass’){
//login successful
}
else {
//login failed
}
?>
Encrypting passwords
To secure the access control you need to implement encryption algorithm on the user login. The PHP function crypt () provides a one-way cryptographic hash function. The prototype for this function is
String crypt (string str [, string salt])
Basic Authentication in PHP
There are some built-in authentication facilities in to HTTP. Scripts or web servers can request authentication from a web browser. The web browser is then responsible for displaying a dialog box or similar device to get required information from the user.
PHP scripts are generally cross-platform, but using basic authentication relies on environment variables set by the server. A sample of HTTP basic authentication using PHP is shown below.
<?php
// if we are using IIS, we need to set $PHP_AUTH_USER and $PHP_AUTH_PW
if(substr($SERVER_SOFTWARE, 0, 9) == ‘Microsoft’ && !isset($PHP_AUTH_USER) && !isset($PHP_AUTH_PW) && substr($HTTP_AUTHORIZATION, 0, 6) == ‘Basic’)
{
list($PHP_AUTH_USER, $PHP_AUTH_PW) = explode(‘:’, base64_decode(substr($HTTP_AUTHORIZATION, 6)));
}
//Replace this if statement with a database query or similar
if($PHP_AUTH_USER!=’user’ || $PHP_AUTH_PW != ‘pass’)
{
// Visitor has not yet given details, or their
// name and password combination are not correct
header(‘WWW-Authenticate: Basic realm=”Realm-Name”‘);
if(substr($SERVER_SOFTWARE, 0, 9) == ‘Microsoft’)
header(‘Status: 401 Unauthorized’);
else
header(‘HTTP/1.0 401 Unauthorized’);
echo ‘You are not authorized to view this resource.’;
}
else {
// visitor provided correct details.
}
?>

