The following login script uses session variables and does not require a database (although that could easily be added I suppose).
It's currently set up for just one user, but that can be modified as well.
It took me forever to figure this out (I'm used to ColdFusion where this is all much easier)... so, hopefully this post will help another PHP newb like me 😉
three files:
index.php - the login form
auth.php - authorization logic
success.php - the "in" page
<?php // index.php ?>
<?php
session_start();
$_SESSION['access'] = "dead";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>cookie login</title>
</head>
<body>
<?
if (!empty($HTTP_SERVER_VARS['QUERY_STRING'])) {
parse_str($HTTP_SERVER_VARS['QUERY_STRING']);
if ($fail==1) {
echo "login failed.<br /><br />\n";
} elseif ($fail==2) {
echo "you must login.<br /><br />\n";
}
}
?>
<form name="someForm" action="auth.php" method="POST">
login <input type="text" name="login"><br />
passwd <input type="password" name="password"><br />
<input type="submit">
</form>
<br />
<?php // for debugging only
echo $_SESSION["access"];
?>
</body>
</html>
<?php // auth.php ?>
<?php
// pass/fail flag for the following logic
$no = 0;
// credentials to be checked against...
// here's where database query file actions would go
$storedLogin = "joe";
$storedPassword = "foo";
if ($_POST['login']!="" and $_POST['password']!="") {
$login = $_POST['login'];
$password = $_POST['password'];
if ($login == $storedLogin) {
if ($password == $storedPassword) {
session_start();
$_SESSION['access'] = "set";
header("Location: success.php");
exit;
} else {
$no = 1;
}
} else {
$no = 1;
}
} else {
$no = 1;
}
if ($no == 1) {
header("Location: index.php?fail=1");
}
?>
<?php // success.php ?>
<?php
session_start();
if (isset($_SESSION['access'])) {
if ($_SESSION['access']=="dead") {
header ("Location: index.php?fail=2");
exit;
}
} elseif (!isset($_SESSION['access'])) {
header ("Location: index.php?fail=2");
exit;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Page title</title>
</head>
<body>
success.
<br /><br />
<a href="index.php">logout</a>
<br /><br />
<?php // for debuggin only
echo $_SESSION["access"];
?>
</body>
</html>