Setup Menus in Admin Panel

  • No products in the cart.

  • LOGIN

PHP Sessions

PHP session stores the information that can be used accross the various pages of an entire website.

A Session is a kind of global variable that is stored on the server.

Unlike a cookie,these details are not saved onto the users computer.

Sessions are a easy way to store data for every users against a unique session ID Session IDs are generally sent to the web browser via session cookies and the ID is used to retrieve session data. The absence of an session ID cookie to PHP know to create and generate a new session ID.

Starting a PHP sessions:

A PHP session is easily started by making a call to the session_start() function. The function first checks if a session is started and if no session is Started then it starts one. It is mandatory to put the call to session_start() at the beginning of the page.

session_start() creates a session and restart the current one bases on a session identifier passed by a GET and POST passed by a cookie.

Syntax:-

bool session_start ( void )

Example:-

session_start();

 

Creating a Session

In order to create a session in PHP, you must first call the PHP session_start function and then store your values in the $_SESSION array variable.

Let’s suppose we want to know the number of times that a page has been loaded, we can use a session to do that.

The code below shows how to create and retrieve values from sessions:

Code:

<?php
session_start(); //start the PHP_session function
if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1;
}
else
{
$_SESSION['page_count'] = 1;
}
echo 'You are visitor number ' . $_SESSION['page_count'];
?>

 

Result:

You are visitor number 1

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Example:−

<?php
unset($_SESSION['counter']);
?>

 

Here is an example which  will destroy all the session variables.

<?php
session_destroy();
?>

ASSIGNMENT : How will you start a session in PHP? MARKS : 10  DURATION : 1 week, 3 days

ASSIGNMENT : How will you destroy the session? MARKS : 10  DURATION : 1 week, 3 days

SEE ALL Add a note
YOU
Add your Comment
 

Advanced Course Search Widget

Popular Courses

Course Categories

© PHPhelp. 2002 - 2018 All rights reserved.
X