PHP Session
In this chapter you will learn:
- Using PHP Sessions to Store Data
- Where the session file stores
- Creating a Session
- Example - Access session data
What is Session
A PHP session stores data on the server, and associates a short session ID string (SID) with that data.
The PHP engine then sends a cookie containing the SID to the browser to store. Then, when the browser requests a URL, it sends the SID cookie back to the server, allowing PHP to retrieve the session data.
The session data is stored on the server. We can store a lot more data in a session than you can in a cookie.
Session file
By default, PHP stores each session's data in a temporary file. The location of the temporary files are specified by the session.save_path in the PHP configuration file.
You can display this value with:
<?PHP
echo ini_get( "session.save_path" );
?>
The session files are often stored in /tmp on UNIX or Linux systems, and C:\WINDOWS\Temp on Windows systems.
The code above generates the following result.
Start
To start a PHP session in your script, simply call the session_start() function.
If this is a new session, this function generates a unique SID for the session and sends it to the browser as a cookie called PHPSESSID (by default).
However, if the browser has sent a PHPSESSID cookie to the server because a session already exists, session_start() uses this existing session.
Because session_start() needs to send the PHPSESSID cookie in an HTTP header, session_start() must be called before outputing anything to the browser, much like you do with setcookie().
<?php
session_start();
?>
Example 1
Before you can add any variables to a session, you need to have already called the session_start() function.
<?php// ja va 2 s .c o m
session_start();
// store session data
$_SESSION['views']=1;
?>
To view a session data.
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
Unlike cookies, session data is available as soon as it is set.
Next chapter...
What you will learn in the next chapter:
- Reading and Writing Session Data
- Store class object
- Example - Checking Session Data
- Example - Removing Session Data
- Example - Storing Complex Data Types