PHP session

PHP SESSIONS

0  0 2016-08-20 07:31:04

Sessions are used to store information on different pages, while using website.
This information is not stored on client’s side, like cookie.

What is a PHP Session?
When you are working with an application or website, you use it, do some wanted changes, and then you save it and close that.
This is similarly to a Session. The computer stores your information.
It remembers when you start the application and when you stop to use it.
But on the internet there is one problem: as the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session provides solution for this problem by storing user information to be used across different pages (e.g. name, email id, etc).
By default, session variables remain until browser is closed by user.

So; Session variables hold information about one single user, and are available to all pages in one application.

Start a PHP Session

A session is always started using the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.

Now, we create a new page called "demo_session.php".

In this page, we will start a new PHP session and set some session variables:
Example
<?php
session_start(); //  session starts
?>

<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["name"] = "name";
$_SESSION["mail"] = “mail";
echo "Session variables are set.";
?>
</body>
</html>

Get values of PHP Session Variable

Next, we will create another page called "demo_session1.php".
From this page, we will get 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:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Name is " . $_SESSION["name"] . ".<br>";
echo "Emial is " . $_SESSION["mail"] . ".";
?>

</body>
</html>

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy():
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>

 

Comments (0)

Post Your Comments

Headquarter



Hong Kong Office



Find Us On

Website Development Company
SEO
Digital Marketing
website development company in Hong Kong
website designer in pune