Now that we know what a session is and why we need to create session, let’s divulge in its details. To begin with, we must understand how to create a session. It is done by using PHP session_start() function.
Things to know about PHP session_start()
- Before creating session variables to store the user data, you need to create a session
- A session is not permanent. When the web application is closed or browser is terminated the existing session will terminate
- A session can be destroyed with session_destroy() function
- A session is like a cookie which is stored in a server. It terminates when the user closes the browser.
- The session ID cookie will be removed automatically when a session is destroyed.
What happens when a session starts?
When a user requests a website URL that maintain sessions a lot of things happen. A PHP session_start() function call in a script will do the following-
- PHP server get the request to create a session
- A unique session ID (SID) for a session is generated
- This session ID is saved in the server
- The session ID is sent to the browser. This session ID is also saved in a cookie with name PHPSESSID for reference by the browser for further communication within the current session with same website.
For all the further requests to the same website the browser looks for cookie (PHPSESSID) locally. If this cookie is set, session_start() uses the session ID stored in the cookie just like a cookie information is sent to server.
The session_start() function has to send the PHPSESSID cookie within the HTTP header as soon as it creates a session. So, it has to be called before the browser gets anything associated with the current session’s data. Here it works like a cookie being set with setcookie() function. The difference is that the session data is maintained by the server.
How to use PHP start_session()?
The PHP session_start() function is called within <?php….?>. This must be done before you define or use any session variables in your PHP scripts.
<?php session_start(); ?>
As soon as you declare a session, the superglobal $_SESSION will be available in all the PHP scripts of your application. Now, you can create, set and access your session variables with $_SESSION as you do with other superglobals.