Skip to content
UoL CS Notes

PHP Sessions

COMP284 Lectures

As no data about a client is remembered by default we can’t track a series of requests from coming from the same user. This can be problematic if we want to send several forms, such as on a shopping site.

Hidden Inputs

One way of solving this is by sending the data from the last form along with the next using a hidden input:

form1.php:

<form action="form2.php" method="post">
	<label>
		Item:
		<input type="text" name="item">
	</label>
</form>

form2.php:

<form action="process.php" method="post">
	<label>
		Adress
		<input type="text" name="address">
	</label>
	<input
		type="hidden"
		name="item"
		value="</php echo $_REQUEST['item'] ?>"
	/>
</form>

As we use $_REQUEST['item'] we can manipulate this value using process.php.

The user is able to modify these hidden fields if they want to act maliciously.

Sessions

This is a way of keeping track of a user’s session by using a session identifier which is:

  • Generated by the server, when the session starts.
  • Remembered by the browser.
  • Sent by the browser with every further HTTP request to that server.
  • Forgotten by the browser when the session ends, or the browser is closed.

In addition, the server can use session variables for storing information that relate to a session.

Session variables only store data temporarily. to preserve data between visits then you need to use a persistent cookie or a database.

Sessions vs. Cookies

Sessions:

  • ID and session data are stored on the web server.
  • Access and changes to session data are done in PHP via the $_SESSION array.
  • Expiration cannot be set; it always expires when the user’s close the browser or the session is ended by a script.
  • The client can’t manipulate the data.

Cookies:

  • ID and cookies data are stored by the web client on the user’s device.
  • Acess to cookie data is done in PHP via the $_COOKIE array.
  • Changes to cookie data are done in PHP via setcookie.
    • Expiration can be set via setcookie too.
  • Web client can be manipulated.

    This can be used as an attack vector.

Session Method

Creating and using sessions uses the following method:

  1. Start the session:
    • session_start()
    • session_id([id])
    • session_regenerate_id([delete_old])
  2. Maintain session data:
    • session_start()
    • The $_SESSION array.
    • isset($_SESSION[key])
  3. End a PHP session:
    • session_destroy()
    • $_SESSION = array();
    • session_unset()
    • setcookie(name, value, expires, path)

Starting a Session

session_start()

session_start()

Creates a session identifier when a session is created:

  • Sets up the $_SESSION array that stores session variables and session data.

The function must be executed before any other header calls or output is procured.

session_id()

session_id([id])

Get or set the session id for the current session:

  • The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs.

session_name()

session_name([name])

Returns the name of the current session:

  • If a name is given, the current session name will be replaces with the given one and the old name returned.

session_regenerate_id()

session_regenerate_id([delete_old])

Replaces the current session id with a new one:

  • By default keeps the current session information stored in $_SESSION.
  • If the optional boolean argument is true, then the current session information is deleted.

Regular use of this function alleviates the risk of a session being hijacked.

Maintaining Session Data

We can use the following methods:

  • session_start()
  • The $_SESSION array.
  • isset($_SESSION[key])

like so:

<?php
// counting the number of page requests in a session
// each web page contains the following PHP code
session_start();
if (!isset($_SESSION['requests']))
	$_SESSION['requests'] = 1;
else
	$_SESSION['requests']++;
echo "#Requests in this session so far: ", 
	$_SESSION['requests'], "<br>\n";
?>

Ending a Session

We can end a session like so:

<?
session_start();
session_unset();
if (session_id() != "" || isset($_COOKIE[session_name()]))
	// force the cookie to expire
	setcookie(session_name(), session_id(), time()-2592000, '/');
session_destroy();
?>

You should only end the session if the operation is successful. This saves losing all existing.

Close on Inactivity

The following code tracks whether a session is active and end the session if there has been no activity for more than 30 mins:

if (
	isset($_SESSION['LAST_ACTIVITY']) &&
	(time() - $_SESSION['LAST_ACTIVITY'] > 1800)
) {
	session_destroy();
	$_SESSION = array();
	if (session_id() != "" ||isset($_COOKIE[session_name()]))
		setcookie(session_name(), session_id(), time()-2592000, '/');
} else {
	$_SESSION['LAST_ACTIVITY'] = time();
}	

We can also use this same construct to make the session identifier change every 30 mins1:

if (!isset($_SESSION['CREATED'])) {
	$_SESSION['CREATED'] = time ();
} else if (time() - $_SESSION['CREATED'] > 1800) {
	// session started more than 30 minutes ago
	session_regenerate_id();
	$_SESSION['CREATED'] = time();
}

Session Examples

  • There is an improved example of the “hidden inputs” example from above using session variables [starting at slide 16]https://liverpool.instructure.com/courses/46944/files/6811254?module_item_id=1325181).

  • There is also a PRG (POST, redirect; GET) example with sessions starting at slide 19.