Remembering Users: Activating Sessions in PHP

Sessions, by default, use a cookie called PHPSESSID. When you start a session on a page, the PHP engine checks for the presence of this cookie and sets it if it doesn’t exist. The value of the PHPSESSID cookie is a random alphanumeric string. Each web client gets a different session ID. The session ID in the PHPSESSID cookie identifies that web client uniquely to the server. That lets the engine maintain separate piles of data for each web client.

The conversation between the web client and the server when starting up a session is illustrated in Figure 10-2.


Figure 10-2. Client and server communication when starting a session

To use a session in a page, call session_start() at the beginning of your script. Like setcookie(), this function must be called before any output is sent. If you want to use sessions in all your pages, set the configuration directive session.auto_start to On. Appendix A explains how to change configuration settings. Once you do that, there’s no need to call session_start() in each page.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *