Latest web development tutorials

PHP Session

PHP session variable is used to store information about a user session (session), or change the user session (session) setting. Session variables to store information about a single user, and are available for applications in all pages.


PHP Session Variables

When you operate an application on your computer, you open it, do some changes, and then close it. It's like a conversation (Session). The computer knows who you are. It is clear that you open and close applications when. However, on the Internet, the question arises: could not hold because the HTTP address, Web server does not know who you are and what you did.

PHP session solves this problem, it is through the user information stored on the server for later use (such as user name, purchases, etc.). However, session information is temporary and will leave the site the user is deleted. If you need to permanently store information, data can be stored in the database.

Session mechanism is: create a unique id (UID) for each visitor and store variables based on this UID to. UID stored in a cookie, or be conducted through the URL.


Start PHP Session

Before you can store user information to the PHP session, you must first start the session.

Note: session_start () function must be in the <html> tag before:

<?php session_start(); ?>

<html>
<body>

</body>
</html>

The code above will register the user's session to the server, so that you can start saving user information, and assign a session for the user UID.


Session variable storage

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

<?php
session_start();
// 存储 session 数据
$_SESSION['views']=1;
?>

<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>

<?php
// 检索 session 数据
echo "浏览量:". $_SESSION['views'];
?>

</body>
</html>

Output:

浏览量:1

In the following example, we create a simple page-view counter. isset () function checks whether the set "views" variable. If you have set "views" variable, we accumulate the counter. If "views" does not exist, create "views" variable, and set it to 1:

<?php
session_start();

if(isset($_SESSION['views']))
{
	$_SESSION['views']=$_SESSION['views']+1;
}
else
{
	$_SESSION['views']=1;
}
echo "浏览量:". $_SESSION['views'];
?>


Destruction Session

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

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

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

You can also call session_destroy () function is the complete elimination of session:

<?php
session_destroy();
?>

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