sessions

Making Use of Sessions

Now, that's all fair enough, but what can you do with it?

If you're using a server-side script to generate pages, then quite a bit. You can take information from a posted form, or in the query string, and add it to the session data. You can then retrieve this information and redisplay it , or save it in the database. You can remove information from the session data, and modify it. And you can do this freely within your scripts.

PHP Sessions Setup

By default, PHP stores session data in files, although it can make us of databases and there are a number of functions that can be used to enhance session handling in scripts. For beginners, though, the default handling is usually enough.

In PHP, there is one initial requirement for using sessions. Every page must call the session_start() function before any information is sent to the client from the server, and before you can actually access the session data.

PHP Sessions Usage

This is about the simplest example of using sessions:

<?php
 
// index.php
 
require_once('/includes/common.php');
 
// page code goes below here
 
 
$page_output = '';
 
if (isset($_GET['forgetme'])) {
 
  if (isset($_SESSION['username'])) {
 
    unset($_SESSION['username']);
 
  }
 
}
 
if (isset($_POST['username'])) {
 
  $_SESSION['username'] = $_POST['username'];
 
}
 
if (isset($_SESSION['username'])) {
 
  $page_output .= '<p>Hello ' . htmlentities($_SESSION['username']) . '!</p>

Sessions - Further Reading

Further, useful, reading on sessions:

PHP

Foundations: Sessions and Session Data

Logging into an online discussion forum and browsing the threads before posting replies to one, some or all, is an activity that most people just do these days without even thinking about it. Even shopping on a site like Amazon, which remembers your shopping basket as you browse for one last book/movie/gewgaw to purchase and get your order total high enough to achieve the free delivery option without even logging in until it comes time to part with your cash is a non-event these days.

Sessions - How Websites Remember Things

Some clever people came up with a method of passing information, such as user login, from one page to another in the early days of the internet.