PHP Introduction | Page Transitions, Cookies, and Sessions | What is a Session?
Cookies help preserve user-specific information, but they have the drawback that they can store only very small amounts of text. Cookies are not suitable when you need to store more data. In such cases, you use a feature called a “session.”
A session is a technique that lets the server and client (web browser) continuously maintain a connection. As described so far, the web is structured so that “each page is independent.” The server and browser communicate each time a page is accessed, but by default they cannot keep continuous information about who the other party is or which page of the website the user is moving from and to.
A session issues a unique ID to the client that accessed the site (this is called a session ID), stores it in a cookie or appends it to the URL, and ensures that this ID is always sent and received when communicating with the server. This ID is then used to identify the user who is currently accessing the site.
By using a session, you can store user-specific information. The server keeps information for a specific session ID, and when the client accesses the server, it retrieves and uses the information stored for that session ID.
Using sessions in PHP is very simple. To start a session, first run:
session_start();
After this function runs, sessions become available. One important point is that this session_start function must also be executed before anything is output.
As explained above, sessions work by storing the session ID in a cookie, so the required information is added to the header and sent. Therefore, if you call session_start after the header has already been sent, sessions cannot be used.
Information stored in a session is organized in the associative array $_SESSION, which is provided by PHP. Unlike $_COOKIE, values in $_SESSION can be read and written. In other words, you can store values in $_SESSION or retrieve them as needed. Because of this, you do not need to account for the timing difference that exists with cookies, where a saved value does not exist yet and is provided only on a later access. You can use it just like an ordinary associative array.