A PHP session variable is used to store information , or change settings for a user session. Session variables hold information about an user, and are available to all pages in one application.
To store user information in a session variable , you need to first start session .
Initialize session data
<?php session_start(); // initiates session $_SESSION['views'] = 1 ; // stores session variable echo $_SESSION['views'] ; // output : 1 print_r($_SESSION) ; // print all the session variables ?>
<?php define("APP_ROOT",'http://trainee.afixiindia.com/'); session_start(); echo 'Welcome to page #1'; $_SESSION['name'] = 'Rasmi'; $_SESSION['dept'] = 'mca'; $_SESSION['college'] = 'Ravenshaw'; echo 'page 2'; session_start(); echo 'Welcome to page #2'; print_r($_SESSION['college']); ?>
<?php define("APP_ROOT",'http://trainee.afixiindia.com/'); session_start(); echo 'Welcome to page #1'; $_SESSION['name'] = 'Rasmi'; $_SESSION['dept'] = 'mca'; $_SESSION['college'] = 'Ravenshaw'; echo 'page 2'; session_start(); echo 'Welcome to page #2'; print_r($_SESSION['college']); Session_destroy(); print_r($_SESSION['college']); ?>
The session_unset() function frees all session variables currently registered.
<?php unset($_SESSION['email']); ?>
session_id() returns the session id for the current session
* session_name() get and/or set the current session name
* session_name() returns the name of the current session.
* If name is given, session_name() will update the session name and return the old session name.
test.php <?php echo "<pre>This is test.php. Run test2.php in another tab(Note: not in other browser)"; define("APP_ROOT",'http://trainee.afixiindia.com/'); session_start(); echo 'Session Starts<br/>'; $_SESSION['name'] = 'Rasmi Ranjan'; $_SESSION['college'] = 'Ravenshaw'; echo 'Value assigned<pre>'; print_r($_SESSION['college']); // session_unset(); session_destroy(); // $_SESSION = NULL; var_dump($_SESSION); print_r($_SESSION['college']); ?>
test2.php <?php echo "<pre>"; session_start(); var_dump($_SESSION); print_r($_SESSION['college']); ?>
A cookie is used to keep information in the user's browser .A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
The main difference between cookie and session is that cookies are stored on the client, while session data is stored on the server .
Eg . If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit.
1.setcookie:Set cookie variable.
<?php $value = 'something from somewhere'; setcookie("TestCookie", $value); setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */ setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */ echo $_COOKIE['TestCookie']; // Output : something from somewhere print_r($_COOKIE) ; // print all the cookies ?>