WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 Sessions


PHP session variables are used to store information about user sessions or to change settings for user sessions. The Session variable stores information for a single user and is available to all pages in the application.


PHP Session variables

When you are working on an application on your computer, you open it, make some changes, and then close it. It's a lot like a Session. The computer knows who you are. It knows when you open and close the application. However, on the Internet, a problem arises: because the HTTP address cannot be maintained, the web server does not know who you are and what you do.

PHP session solves this problem by storing user information on the server for later use (such as username, purchase, etc.). However, session information is temporary and will be deleted after the user leaves the website. If you need to store information permanently, you can store the data in a database.

Session works by creating a unique id (UID) for each visitor and storing variables based on this UID. The UID is stored in a cookie or transmitted via a URL.


Start PHP Session

Before you store user information in a PHP session, you must first start a session.

Note: The session_start () function must be located <html> Before labeling:

Examples

<?php session_start(); ?> <html> <body> </body> </html>

The above code registers the user's session with the server so that you can start saving user information and assigns a UID to the user session.


Storing Session variables

The correct way to store and retrieve session variables is to use the PHP $ _SESSION variable:

Examples

<?php session_start(); // Store session data $_SESSION['views']=1; ?> <html> <head> <meta charset="utf-8"> <title>welookups Tutorial(welookups.com)</title> </head> <body> <?php // Search session data echo "Page views:". $_SESSION['views']; ?> </body> </html>

Output:

  Pageviews:   1  

In the example below, we created a simple page-view counter. The isset () function detects whether the "views" variable has been set. If the "views" variable is set, we increment the counter. If "views" does not exist, create "views" variable and set it to 1:

Examples

<?php session_start(); if(isset($_SESSION['views'])) { $_SESSION['views']=$_SESSION['views']+1; } else { $_SESSION['views']=1; } echo "Page views:". $_SESSION['views']; ?>


Destroy Session

If you want to delete some session data, you can use the unset () or session_destroy () function.

unset () function is used to release the specified session variable:

example

<?php session_start(); if(isset($_SESSION['views'])) { unset($_SESSION['views']); } ?>

You can also completely destroy the session by calling the session_destroy () function:

example

<?php session_destroy(); ?>

Note: session_destroy () will reset the session and you will lose all stored session data.