Archive

Posts Tagged ‘lolz’

Simple $_SESSION Tutorial

March 12th, 2009 admin No comments

In this tutorial, we’ll speak about the $_SESSION tool and how it can be effective in securely storing data!

What are sessions good for:

  • Storing Login Information
  • Storing User Information
  • Checking if User is Logged In

The list goes on but those are just a few possibilites.

Today, I’m going to write an example on how to use them and set a time when to automatically log the user out!

First, we’ll make the init.php. This will hold our “session_start();” variable (located at the beginning – this file must be included in all other files in which you want sessions to carry over)

<?php
/**
* Simple Sessions Script by Dennis M.
*
* File: init.php
* Desc: To do most of the session handling
*
* Author: Dennis M.
*
*/
session_start(); // Must come first so this works
// Let's see if the user is logged in!
if(isset($_SESSION['user'])){
// Apparently the user is logged in. So let's check if the session has expired. We'll set it to 5min expiration if idle (300 seconds)
if(time() &gt;= $_SESSION['time']+300){
session_destroy();
print "Your session has expired!";
exit;
}
$_SESSION['time'] = time(); // User passed the testing! :D Let's reset their time.
}
define("SCRIPT",true); // Simple definition to allow security access to our functions.php :)

?>

Now that we have created that file, we can create the functions which will make this all work properly. We’ll call this “functions.php”
<?php
/**
* Simple Sessions Script by Dennis M.
*
* File: functions.php
* Desc: Make the sessions work! :)
*
* Author: Dennis M.
*
*/
// This is what that init.php definition was for! ;)
if(!defined("SCRIPT")){
print "Unauthorized access!";
exit;
}

class Login_Base
{
/**
* Our constructor!
*
*/
function __construct(){
// Just our MySQL Info ;) - DB structure is at the end of the post!
mysql_connect("localhost","USER","PASS");
mysql_select_db("DB_NAME");
// Almost forgot. Define a prefix for the db!
$prefix = "sestut";
}
/**
* Let's Register the user!
*
*/
function register($user,$pass){
// Let's check if the user exists. If so, let's not overwrite :) plz and thanks
$query = mysql_query("SELECT * FROM ".$prefix."_users WHERE user='".mysql_escape_string($user)."'");
if(mysql_num_rows($query) > 0){
return false;
}
// Seems all is well. Let's make the user...
$pass = md5($pass); // Simple encryption.. Hold the salt please...
$query = mysql_query("INSERT INTO ".$prefix."_users (`id`, `user`, `pass`) VALUES (NULL, '".mysql_escape_string($user)."', '".$pass."')");
if(!$query){
print "MySQL Error: ".mysql_error();
return false;
}
return true;
}
/**
* Now login :)
*
*/
function login($user,$pass){
// Check for everything now!
$query = mysql_query("SELECT * FROM ".$prefix."_users WHERE user='".mysql_escape_string($user)."' AND password='".md5($pass)."'");
if(mysql_num_rows($query) == 0){
print "Invalid login credentials!";
return false;
}
// Passed the test :D Let's set everything...
$_SESSION['user'] = $user;
$_SESSION['time'] = time(); // This is important for expiration handling ;)
return true;
}
}

?>

Our functions are now fixed up nicely. Time for the index page! We’re not going to be diving into SEO friendly URLs for this one, so we’re going to use a standard ?page=ACTION style link. But we’ll make due ;)

<?php
/**
* Simple Sessions Script by Dennis M.
*
* File: index.php
* Desc: Use what was created earlier!
*
* Author: Dennis M.
*
*/
include_once("init.php"); // VERY Important that this is included FIRST! (BEFORE any other code - not including comments)
include_once("functions.php"); // Our functions
$login = new Login_Base; // Define a variable to point to the class and functions...// Define default page for users not logged in or if the page is not directed to registration
if(!isset($_SESSION['user']) && $_GET['page'] != "register" && !isset($_POST['form'])){
print "<form name=\"login\" method=\"post\" action=\"?page=login\">
<p>Username: <input type=\"text\" name=\"user\" /></p>
<p>Password: <input type=\"password\" name=\"pass\" /></p>
<p><input type=\"submit\" value=\"login\" /></p>
<input type=\"hidden\" name=\"form\" value=\"true\" />
</form>
<p>Register Now!</p>";
exit;
}
// Default everything out :)
if(!isset($_GET['page'])){
$_GET['page'] = "index";
}
switch(strtolower($_GET['page'])){
default:
print "<p>The login has been successful!<br /><br />
Your username is: ".$_SESSION['username']."<br /><br />
Please proceed with the following:<br />
Test page 2 (Separate page to show that it carries)<br />
Logout</p>";
break;
case 'logout':
if(session_destroy()){
print "Successfully logged out!";
exit;
} else {
print "There was an error logging out!";
exit;
}
break;
case 'register':
if($_GET['act'] != "go"){
print "<form name=\"register\" method=\"post\" action=\"?page=register&act=go\">
<p>Username: <input type=\"text\" name=\"user\" /></p>
<p>Password: <input type=\"password\" name=\"pass\" /></p>
<p><input type=\"submit\" value=\"Register\" /></p>
</form>";
} else {
if($login->register($_POST['user'],$_POST['pass'])){
print "Registration successful! You can now login!";
} else {
print "Registration failed!";
}
}
break;
case 'login':
if($login->login($_POST['user'],$_POST['pass'])){
print "Login successful! Please go back home";
exit;
} else {
print "Login failed!";
exit;
}
break;
}
?>

Now one final test to make sure everything is working properly. A simple “test.php” should do! Just another file to show sessions are being properly handled.

<?php
/**
* Simple Sessions Script by Dennis M.
*
* File: test.php
* Desc: Wrapping things up now. Name implies it all :)
*
* Author: Dennis M.
*
*/
include_once("init.php"); // Again very important to include first

// Check if user logged in..if(!isset($_SESSION['user'])){
print "Uh-oh, you're not logged in! Try going here to login!";
exit;
}

print "Great, you're logged in!<br /><br />Username: ".$_SESSION['user']."<br /><br />Return to index";
?>

As mentioned earlier, I’d give the database structure as well. What I use by default is the name ‘sestut_user’ for the table but you can do whatever you like! (Provided that you properly modify the code to do so)
CREATE TABLE `users` (
`id` BIGINT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user` VARCHAR( 32 ) NOT NULL ,
`password` VARCHAR( 32 ) NOT NULL
) ENGINE = MYISAM ;

Regards,
Dennis M.