PHP Session

A session is a more secure way of talking to a client(a server). Once the session has been opened, the session can be used(maintained) on any page of the site, creating a "conversation" mechanism between the visitor and the site.

Common online shopping cart is a typical session. When we scheduled the goods, will choose a good product into the shopping cart, the actual is to open a commodity session. If the order is placed on the selected goods, the corresponding information will be written to the database; if the final order is not placed in the user to close the browser or exit the landing, it will close the session, the selected goods expire immediately.

A session will establish a unique session ID for each visitor who opens a session to identify the user. The session ID may be stored in the cookie of the user's computer or may be passed through the URL. And the corresponding specific session value will be stored on the server side, which is the main difference with the cookie, and security is relatively high.

Create session

to create a session, you must first use session_start() function to open a session, the system will assign a session ID:


use the session_register() function to register a session variable that returns TRUE, otherwise returns FALSE.


bool session_register(mixed name[, mixed ...])

you can use the session_register() function to register one or more global session variables under the current session.


$username = "Selema";
Session_register("username ");

In this example, we registered a variable named username with a value of Selema.

Read session

PHP built-in $_SESSION variable can be easily set to access the session variables.


$'SESSION["username"]; // The registered user name is: Selema

Destroy session

you can use the session_unregister() function to unregister a single session variable or use session_unset() to log out the entire session.


Session_unregister("username "); // Log out of session variables
session_unset(); // Log out of the session

Another way

You can register the session variable by adding the $_SESSION array member directly:

$_SESSION["username"] = "Selema";

If you want to log out of session variables registered in this way, you need to use the unset() function:


Reading session variables and destroying sessions is the same as before.


you can not use unset() to destroy a session.

Copyright 2014-2017 by All Rights Reserved.