PHP Sessions
- Previous Page PHP Cookies
- Next Page PHP E-mail
PHP session variables are used to store information about user sessions or to change the settings of user sessions. The information saved by session variables is for a single user and can be used by all pages in the application.
PHP Session Variables
When you run an application, you open it, make some changes, and then close it. This is very much like a session. The computer knows who you are. It knows when you start the application and when you terminate it. But on the internet, there is a problem: the server does not know who you are or what you are doing, which is due to the fact that HTTP addresses cannot maintain state.
PHP session solves this problem by storing user information on the server for later use (such as user name, purchased products, etc.). However, session information is temporary and will be deleted when the user leaves the website. If you need to store information permanently, you can store the data in a database.
The way Session works is: it creates a unique id (UID) for each visitor and stores variables based on this UID. The UID is stored in a cookie or transmitted through the URL.
Start PHP Session
You must start the session first before you store user information in the PHP session.
Note:The session_start() function must be placed before the <html> tag:
<?php session_start(); ?> <html> <body> </body> </html>
The above code registers the user's session with the server, so you can start saving user information, and also assigns a UID to the user session.
Store Session Variables
The correct method to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html>
Output:
Pageviews=1
In the following example, we create a simple page-view counter. The isset() function checks if the "views" variable has been set. If the "views" variable has been set, we increment the counter. If "views" does not exist, we create the "views" variable and set it to 1:
<?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?>
Terminate Session
If you want to delete some session data, you can use the unset() or session_destroy() function.
The unset() function is used to release the specified session variable:
<?php unset($_SESSION['views']); ?>
You can also completely terminate the session through the session_destroy() function:
<?php session_destroy(); ?>
Note:session_destroy() will reset the session, and you will lose all stored session data.
- Previous Page PHP Cookies
- Next Page PHP E-mail