Forum Moderators: coopster
I have a logon for the directory call "widgets". This directory contains semi-sensitive materials, that the general public doesn't need to see. So I have a list of files here:
index.php -- where thbase of my authentication is
include.inc -- an include file, hidden way high up in my server root, above the web root and accessible only with administrative privileges. This file contains my usernames and passwords in comma seperated values ie John,hispass.
and the rest of my files
widgets1.php
widgets2.php
widgets3.php
widgets4.php
widgets5.php .. etc
index.php
contains the following code:
<?php
session_start();
ob_start();
function auth($user, $pass)
{
include ('include.inc');
$users = array();
foreach ($MyArray as $value)
{
list($uid, $pss) = split('[,.-]', $value);
$users[$uid] = $pss;
}
if (isset($users[$user]) && ($users[$user] == $pass))
{
return true;
}
else
{
return false;
}
}
if (! auth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']))
{
header('WWW-Authenticate: Basic realm="My Website"');
header('HTTP/1.0 401 Unauthorized');
echo "NOT AUTHORIZED!";
exit;
}
$_SESSION['loggedin'] = true;
?>
<html>
Authorized users will see this!
</html>
Now you see the include.inc contains a list of users and passes like mentioned above, however they are listed as such:
<?
$MyArray[] = "user1,pass";
$MyArray[] = "user2,pass";
$MyArray[] = "user3,pass";
$MyArray[] = "user4,pass";
?>
The rest of my files at the top include a small script that checks for authorization... and that is:
<?php
session_start();
ob_start();
if (!isset($_SESSION['loggedin']))
{
$redirect_url = "index.php";
header("Location: $redirect_url");
}
ob_end_flush;
?>
<html>
Authorized users see this!
</html>
#################
I hoped to get this on the web so that there may be a more detailed sample for people who don't get the samples given by php.net and such, as they don't give an example of comparing the username:pass, just the PHP_AUTH basics. It took me a few hours of searching and playing to get this figured out. If there is something I can add, or do to make this better, I would love to hear from you, and others like me searching the web will appreciate it!
-- Zak
very nice work though, lZakl
<added>I think I might change this
if (! auth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']))
{
header('WWW-Authenticate: Basic realm="My Website"');
header('HTTP/1.0 401 Unauthorized');
echo "NOT AUTHORIZED!";
exit;
}
$_SESSION['loggedin'] = true;
to have $_SESSION['loggedin'] set in an else, seems silly but I like things like that to very very explicit and not a coding error allow a drop through were people get logged in automatically.
About the only security note I would make is to use require ('include.inc');
I might even say require_once ...
Nice! Just the sort of tips I was looking for!
jatar_k,
You mention setting $_SESSION['loggedin'] in an else. Would it be benificial to include my HTML in that same else?
Thanks for your input guys!
-- Zak