PHP Basic Tutorial
MySQL Connection
PHP Advanced
PHP sessions are a way to store information (variables) to be used across multiple pages.
Unlike cookies, which are stored on the client-side (in the browser), session data is stored on the server.
This allows for better security, as sensitive information isn't exposed to the client-side (browser).
To use sessions in PHP, you need to call session_start()
at the beginning of the script. This function must be called before any output (HTML, text, etc.) is sent to the browser.
Now, let's create a new page called "demo_session.php". In this page, we start a new PHP session and set some session variables:
Next, we create another page called "get_session.php". From this page, we will access the session information we set on the first page ("demo_session.php").
Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()
).
Also notice that all session variable values are stored in the global $_SESSION variable:
Another way to show all the session variable values for a user session is to run the following code:
Modifying a session variable in PHP is simple. After starting the session using session_start()
,
you can change the value of any session variable directly by assigning a new value to it.
Destroying a session in PHP involves removing all session data and optionally removing the session cookie. The process includes two main steps:
This ensures that the session is completely destroyed, and no session data remains accessible.
Note
Use session_unset() when you want to clear session data but keep the session alive (e.g., removing user data after a form submission).