PHP Session_Start() Function

A Cookie by Any Other Name...

In PHP, information designated for use across several web pages can be stored in a session. A session is similar to a cookie, but the information contained in the session is not stored on the visitor's computer. A key to open the session—but not the information contained within—is stored on a visitor's computer. When that visitor next logs in, the key opens the session. Then when a session is opened on another page, it scans the computer for the key.

If there is a match, it accesses that session, if not it starts a new session.

With sessions, you can build customized applications and increase the usefulness of the site to its visitors. 

Every page that will use the session information on the website must be identified by the session_start() function. This initiates a session on each PHP page. The session_start function must be the first thing sent to the browser or it won't work properly. It must precede any HTML tags. Usually, the best place to position it is right after the <?php tag. It must be on every page you intend to use.

The variables contained in the session—such as username and favorite color—are set with $_SESSION, a global variable. In this example, the session_start function is positioned after a non-printing comment but before any HTML.

 <?php // this starts the session session_start(); // this sets variables in the session $_SESSION["test"]="testing"; $_SESSION['favcolor'] = 'blue'; // Works if session cookie was accepted; echo '<br /><a href="page2.php">page 2</a>';  ?/

In the example, after viewing page 1.php, the next page, which is page 2.php, contains the session data and so on. The session variables end when the user closes the browser.

Modifying and Deleting a Session

To modify a variable in a session, just overwrite it. To remove all the global variables and delete the session, use the session_unset() and session_destroy() functions.

Global vs. Local Variable

A global variable is visible throughout the program and it can be used by any function in the program. A local variable is declared inside a function and that is the only place it can be used. 

To learn more about the functions available in PHP, check out the PHP tutorial here.