I did a script just like this a little while ago and here it is:
<?php
function cookieTest($login, $pass){
if (isset($login) && isset($pass)){
databaseTest($login, $pass);
}else{
include "loginform.html";
exit;
}
}
function login($login, $password){
databaseTest($login, $password);
setcookie("cookiename","$login",time()+33177600, "/", "domain");
setcookie("cookiepass","$password",time()+33177600, "/", "domain");
}
function databaseTest($login, $password){
$dbhost = "localhost";
$dbuser = "dbuser";
$dbpass = "dbpass";
$dbname = "dbname";
$dbtable = "dbtable";
$dblink = mysql_connect($dbhost, $dbuser, $dbpass);
if (! $dblink){
die("Couldn't connect to database: ".mysql_error());
}
mysql_select_db($dbname, $dblink) or die("Couldn't opem $db: ".mysql_error());
$result = mysql_query("SELECT * FROM $dbtable");
$testnum = (mysql_num_rows($result) - 1);
while ($val = mysql_fetch_assoc($result)){
$loginarray[] = $val["loginname"];
$passwordarray[] = $val["password"];
$emailarray[] = $val["emailaddy"];
}
mysql_close($dblink);
for ($i = 0; $i<=$testnum; $i++){
if ($loginarray[$i] == $login){
if ($passwordarray[$i] == $password){
$logingood = true;
break;
}else{
$logingood = false;
break;
}
}
}
if ($logingood){
return true;
}else{
echo("Login failed.");
exit;
}
}
// functions end
// main script
if ($action == "login"){
login($login, $password);
}else{
cookieTest($cookiename, $cookiepass);
}
?>
Basically this file is just included in any page and if they are logged in it does nothing but if they aren't logged in it presents them with a form to login. Here is the loginform.html I used:
<html><head><title>Login</title></head><body><div align="center">
<form method="post" name="login" action="?action=login">
<input type="text" name="login" size="25" value="Login"><br>
<input type="text" name="password" size="25" value="Password"><br>
<input type="submit" value="Login"></form></div></body></html>
You will of course need to edit the script some with your database info. Only main problem with the script is that it stores the password in the open without encrypting it or anything. That is something I was planning to add but never got around to it. Also I am willing to bet that someone who isn't as new to PHP as I am could probably write a much more streamlined version but this one gets the job done. Actually just looking at it now I see a few ways to improve it but this should get you started.