Dynadot

[TUTORIAL] PHP Sessions

NameSilo
Watch
Here is a simple PHP sessions tutorial I put together! It's pretty fleshed out in notations. This is all assuming you've seen my previous tutorials explaining classes, pointers, etc! Enjoy!

-RageD

functions.php
PHP:
<?php
/**
 * Simple Sessions Tutorial by RageD
 *
 * (C) RageD 2009. All Rights Reserved.
 *
 *
 * All of our simple functions will be held here! :D
 * All the login/logout will be carried out. Perhaps later
 * I'll add on with a MySQL version so you can checkAuth();
 * against a db, etc!
 *
 */
if(!defined("AUTH_ACCEPT"))
{
  echo "Unauthorized Access!";
  exit;
}

class Session
{
  /**
   * Login
   *
   * Starting right on it :) No need for a __construct();
   * or other variables to be defined because this isn't a
   * large project carrying from multiple files, functions,
   * classes, etc.! :)
   *
   */
  function login($user,$pass)
  {
    // Here we will completely carryout the login function
    // according to data inserted. Since we aren't logged
    // into a DB this is going to be static and only allow
    // as many as you define.
    if($user == "Test" AND $pass="w00t" OR $user == "User2" AND $pass == "pass2")
    {
      $_SESSION['username'] = $user; // Sets the session data username = to $user
      print "Login Successful! Go back <a href=\"?page\">home</a>"; // Prints msg
    } else {
      print "Invalid login credentials!"; // Prints msg
      return false;
    }
    return true;
  }

  /**
   * Logout
   *
   */
  function logout()
  {
    // Unbelievably simple but... Yep, that's it! ;)
    session_destroy(); // Destroys session
    print "Logout Successful!"; // Prints message
    return true;
  }

  /**
   * CheckAuth
   *
   * Again, no DB so no checking for permissions
   * only for session data really :)
   *
   */
  function checkAuth()
  {
    if(!$_SESSION['username'])
    {
      print "You must be logged in!";
      return false;
    }
    return true;
  }
}
?>

init.php (Most important document! Makes everything run seemlessly)
PHP:
<?php
/**
 * Simple Sessions Tutorial by RageD
 *
 * (C) RageD 2009. All Rights Reserved.
 *
 * This has to be the first thing included in all documents for them
 * to hold session data.
 *
 * Also, (besides comments such as this) session_start(); must start this
 * this document before anything else!
 *
 */
session_start();

// Make sure people can't just go into private files :) (E.g.: functions.php)
define("AUTH_ACCEPT", true);

/**
 * Normally more information would be in here but since we're just handling
 * sessions, not much more is necessary :)
 *
 */
?>

index.php
PHP:
<?php
/**
 * Simple Sessions Tutorial by RageD
 *
 * (C) RageD 2009. All Rights Reserved.
 *
 * Main index script! :)
 *
 */
// Needs to be included first remember:
require_once("init.php");

// Include functions!
require_once("functions.php");

$session = new Session; // Declare our session and how we're going to call ptrs
$page = $_GET['page']; // Declare this to input multiple pages in this doc :)
switch($page)
{
  default:
    if(!$_SESSION['username'])
    { // Basically meaning if user is not logged in!
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form name="login" method="post" action="?page=login">
<p>User: <input type="text" name="user" /></p>
<p>Pass: <input type="password" name="pass" /></p>
<p><input type="submit" value="Login" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
<?php
    } else {
?>
<html>
<head>
<title>Home (User: <?php echo($_SESSION['username']); ?> Logged in!)</title>
</head>
<body>
<h2>Options:</h2>
<p><a href="test.php">Test to see if session works on multiple pages</a></p>
<p><a href="?page=logout">Logout</a></p>
</body>
</html>
<?php
    }
  break;
  case 'login':
    $session->login($_POST['user'],$_POST['pass']);
  break;
  case 'logout':
    $session->logout();
  break;
}
?>
 
Last edited:
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
test.php
PHP:
<?php
/**
 * Simple Sessions Tutorial by RageD
 *
 * (C) RageD 2009. All Rights Reserved.
 *
 *
 * Just a simple test document to prove that
 * the sessions will work across the entire 
 * website as long as "init.php" is loaded
 * first thing!
 *
 */
require_once("init.php");
$page = $_GET['page'];
if(!$_SESSION['username'])
{
?>
<html>
<head>
<title>No user logged in</title>
</head>
<body>
<p>Since no user is logged in, this page is useless :)<br /><br />
Please go back <a href="index.php">here</a> and login with the following credentials
to successfully login and use this page.</p>
<p></p>
<p>User 1<br />
User: Test<br />
Pass: w00t<br /><br />
User 2<br />
User: User2<br />
Pass: Pass2</p>
</body>
</html>
<?php
} else {
?>
<html>
<head>
<title>User: <?php echo($_SESSION['username']); ?> - Logged In!</title>
</head>
<body>
<p>See, it works properly! :) You're logged in with the username <?php echo($_SESSION['username']); ?>. 
Nothing special here but this message. You can go back home <a href="index.php">here</a>. I guess I can
throw a little server grabbing in here too.</p>
<p>Since we don't have a database nothing will be logged and therefore making it pointless to add
how many logins the account has had.</p>
<p>So... I guess I can show you your IP address! :)<br /></p>
<p>Your IP Address: <?php echo($_SERVER['REMOTE_ADDR']); ?><br /><br />Enjoy,<br />RageD</p>
</body>
</html>
<?php
}
?>
 
0
•••
0
•••
Could you make it a bit advanced...

Can you make a legend about the colors ?!
As I see we can skip the things in orange but the other things ?
:-/ a bit but thanks anyways!
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back