The PHP session variable is used to store information about user sessions, or to change settings for user sessions. The session variable holds information that is single user and is available to all pages in the application.
PHP Session Variable
When you run an application, you open it, make some changes, and then close it. It's like a conversation. The computer knows who you are. It knows when you start the application and when it terminates. But on the internet, there is a problem: the server does not know who you are and what you do, because the HTTP address is not maintained.
The PHP session solves this problem by storing user information on the server for subsequent use (such as user name, purchase item, etc.). However, session information is temporary and will be deleted after the user leaves the site. If you need to store information permanently, you can store the data in a database.
The session works by creating a unique ID (UID) for each visitor and storing the variables based on this UID. The UID is stored in a cookie or transmitted through a URL.
Start PHP Session
Before you store the user information in the PHP session, you must first start the conversation.
Note: the Session_Start () function must precede the <html> label:
<?php session_start ()?> <html> <body> </body> </html>
The code above registers a user's session with the server so that you can start saving user information while assigning a UID to the user's session.
Store Session Variable
The correct way to store and retrieve session variables is to use PHP $_session variables:
<?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 created a simple page-view counter. The Isset () function detects whether the "views" variable is set. If you have set the views variable, we add 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 '];?> End Session
If you want to delete some session data, you can use the unset () or Session_destroy () function.
The unset () function frees the specified session variable:
<?php unset ($_session[' views ');?>
You can also completely end the session through the Session_destroy () function:
<?php Session_destroy ();?>
Note: Session_destroy () resets session, and you lose all stored session data.