Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL

Home > PHP > Session Variablesprinter version

PHP Session Variables

HTTP was designed to be as open as possible but the drawback is that there is no persistence of variables across web requests.

When a request is sent to a web server for a resource, the server doesn't know or care if the request comes from someone already on the server or from someone logging in from outside.

Therefore if a web site needs to maintain state, and allow data to be shared across pages, HTML pages won't do it.

Using a Query String

PHP does allow variables to be passed from page to page using a query string as in the example below.

<?php
    echo('<a href="next_page.php?name=Dave&amp;occupation=Programmer">next page</a>;
?>


In some cases this is appropriate, however it's not very convenient where lot's of variables are involved and it's also not secure since the query string shows in the browser's address box.

Using Session Variables

A more elegant and secure solution is to use PHP session variables. Sessions are like server-side cookie files that store variables that can be read from, or written to, by PHP scripts.

Each session file is unique to the user request that created it and can only be accessed by subsequent requests from the same user.

This means that variable values can be unique to each user allowing passwords etc. to be passed from script to script.

Starting a Session

Before any session operations can be carried out, including reading from and writing to session variables, a session must be started. This will allow session variables to hold values unique to each user.

Starting a Session
<?php
    session_start();
?>


Note: session_start() MUST appear before session variables are accessed and on every page that they are required to be accessed.


Using session_start() does one of two things.



When a session is created, PHP session management generates a session identifier that consists of a random 32 hex digit string and creates an empty session file on the server with the name sess_ followed by the session identifier.

It also includes a set-cookie in the response and a session cookie in the browser with the value of the session identifier.

This means that any subsequent request to the server will include this session identifier allowing PHP to connect to the appropriate session file.

Creating Session Variables

To create a session variable session_register("variable_name") is used where variable_name is the name of the variable to be created.

Creating Session Variables
<?php
    session_start();
    session_register ("name");
    session_register ("occupation");
    $name = "Dave";
    $occupation = "Programmer";
?>


The code above first connects to the existing session (using the session identifier from the user's browser that is included with the request) or creates a new session.

It then creates two session variables and sets their values.

Once a session variable has been registered it can then be used like any other PHP variable.

Updating Session Variables

If you update a session variable within a script there's no need to specifically update the session file, session management does this automatically before the script ends.

<?php
    session_start();
    $name = "John";
    $occupation = "Web Developer";
?>


In the example above the session variables are updated in the same way as if they were normal PHP variables except that session_start() is used to connect to the session file.

Session variables are available to any PHP script that connects to the session using session_start() at the beginning of the script.

Destroying Session Variables

Session variables can be destroyed by using session_unregister();

Unregistering Session Variables
<?php
    session_start();
    session_unregister ("name");
    session_unregister ("occupation");
?>


Ending a Session

To end a session the session file is deleted.

Destroying a Session
<?php
    session_destroy();
?>


PHP Sessions vs. JavaScript Cookies

In many cases a similar result can be achieved by using JavaScript cookies, however PHP sessions have some advantages.



Previous - PHP file functions Previous - File Functions


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
PHPBasicsCreating a ScriptRunning a ScriptVariablesExpressions and OperatorsStringsStrings and SubstringsReplacing SubstringsRegular ExpressionsBranches and ConditionsLoopsArraysArray FunctionsSorting ArraysUser-Defined FunctionsInclude and RequireUploading FilesFile FunctionsPHP session variablesSession Variables
Recommended Reading
PHP and MySQL web development

programming PHP

PHP cookbook
Tips and TricksPage TemplatesForm Reply ScriptsForm ValidationJavaScript to PHP
Got any PHP Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.