Differentiation of users
In the above page, everybody has access to the restricted part since they enter with the same username and password. Evidently, this is not a good solution, it is better for every person to have their own username and password because this allows us to restrict a user without compromising the security of the site.
In this page we will consider the way to perform this by having a separate file with valid usernames and passwords. Said file could have the following form: user_name|password. For example
passwords.txt
Joe|1235
Pedro|qwer
Noe|Gty45e
kermit|rwe4v
In this example, authorization is requested at the beginning of the page if not previously established and it is verified with the password file that we have called passwords.txt, if the username and password match any entry in the file, we are granted access to the rest of the page.
<?php // Manual de PHP de WebEstilo.com
if (!isset($PHP_AUTH_USER)) {
header('WWW-Authenticate: Basic realm="Acceso restringido"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required.';
exit;
}
$fich = file("passwords.txt");
$i=0; $validado=false;
while ($fich[$i] && !$validado) {
$campo = explode("|",$fich[$i]);
if (($PHP_AUTH_USER==$campo[0]) && ($PHP_AUTH_PW==chop($campo[1]))) $validado=true;
$i++;
}
if (!$validado) {
header('WWW-Authenticate: Basic realm="Acceso restringido"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required.';
exit;
}
?>
<!-- PHP Tutorial WebEstilo.com -->
<html>
<head>
<title>PHP Example</title>
</head>
<body>
Ha conseguido el acceso a la <B>zona restringida</B> con el usuario <?php echo $PHP_AUTH_USER?>.
</body>
</html>