Showing posts with label session_start(). Show all posts
Showing posts with label session_start(). Show all posts

Thursday 21 June 2012

PHP Session


Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:


<?php session_start(); ?>
<html>
<body>

</body>
</html>

Storing a Session Variable

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

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>

Echo a Session Variable
 
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>

Output:
Pageviews=1 

Destroying a Session

 The unset() function is used to free the specified session variable:
 

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


You can also completely destroy the session by calling the session_destroy() function:


<?php
session_destroy();
?>


Note: session_destroy() will reset your session and you will lose all your stored session data.