Running Membership with Sessions
In the first page, I stated that sessions are usually used to create a membership management. Now, I want to show you a little snippet to create a login system, which you have to complete to create your own membership management.
<?php
// functions.php
function secure () {
if (!($_SESSION["member_id"]) || ($_SESSION["member_id"] == "")) {
Header("Location: ./login.php");
exit();
}
}
function login_check ($forms) {
$error = "";
$username = $forms["username"];
$password = $forms["password"];
if (trim($username) == "") $error .= "<li>Your username is empty.</li>";
if (trim($password) == "") $error .= "<li>Your password is empty.</li>";
/* from here, do your sql query to query the database to search for existing record with correct username and password */
if (trim($error)!="") return $error;
}
function login ($forms) {
$username = $forms["username"];
$password = $forms["password"];
/* do your sql query again, but now returning the id of member */
return $member_id;
}
?>
<?php
// login.php
session_start();
include ("functions.php");
if ($_POST) {
$error = login_check($_POST);
if (trim($error)=="") {
$_SESSION["member_id"] = login($_POST);
Header("Location: ./index.php") // Redirect correct member
exit();
} else {
print "Error:$error";
}
}
?>
<form method="post">
Username : <input type="text" name="username"><br />
Password : <input type="password" name="password"><br />
<input type="submit" value="Login">
</form>
<?php
// index.php
include("functions.php");
session_start();
secure();
?>
In the above example, we have built three pages. The first page is functions.php. In this page we build all the functions to do login checking, the login and the login detector.
The second page is login.php. We will show the login form to our user and do some processes to register sessions when they have passed the login check.
Third and the last page is the sample of how to use the system. This page is only available when user has logged in or has the session variable "member_id" with some value, not null.
Source:
http://codewalkers.com/tutorials/32/3.html