How to create a session variable
Today we are going to create a session variable on one page and retrieve the value of it on a second page.
First let's create the first page and call it page1.php. Insert the following code:
//start the session
session_start();
$_SESSION["items_in_cart"] = "2";
The session_start() code registers the visitors's session with the server.
Make sure that you place the session_start() code at the beginning of your script.
How to retrieve a session variable
Now let's create another page and call it page2.php and insert the following code:
session_start();
echo "The total number of items in the cart is $_SESSION["items_in_cart"]";
The above code will output:
The total number of items in the cart is 2
How to destroy a session variable
To destroy a session variable simply use the unset command.
session_start();
//remove all the variables in the session
unset($_SESSION["items_in_cart"]);
//destroy the session
session_destroy();
echo "The total number of items in the cart is $_SESSION["items_in_cart"]";
The above code will output:
value

0 comments:
Post a Comment