PHP Session_Start() Function

programmer reading computer codes on desktop PC.
skynesher / Getty Images

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.

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. 

Format
mla apa chicago
Your Citation
Bradley, Angela. "PHP Session_Start() Function." ThoughtCo, Feb. 16, 2021, thoughtco.com/sessionstart-php-function-2694087. Bradley, Angela. (2021, February 16). PHP Session_Start() Function. Retrieved from https://www.thoughtco.com/sessionstart-php-function-2694087 Bradley, Angela. "PHP Session_Start() Function." ThoughtCo. https://www.thoughtco.com/sessionstart-php-function-2694087 (accessed March 28, 2024).