08_PHP_Lecture
08_PHP_Lecture
COOKIES Consultancy
SESSION IN PHP
web Engineering ||
winter 2017
wahidullah Mudaser Lecture 08
[email protected]
Cookies & Session
INDEX
Cookies
Brief overview
Limitation
Privacy
Type of cookies
Manage cookies
Sessions
Brief overview
HTTP Session Token
Session Advantages
S
PHP Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value “Ahmad".
The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is
available in entire website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE).
We also use the isset() function to find out if the cookie is set:
Example
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Ahmad";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];}
?>
<p><strong>Note:</strong> You might have to reload the page to see the value of the
cookie.</p>
</body>
</html>
DELETE COOKIE
PHP SESSION
When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session.
The computer knows when you start the application and when you end.
But on the internet there is one problem: the web server does not know who you
are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc).
By default, session variables last until the user closes the browser.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Example:
Get PHP Session Variable Values
Notice that session variables are not passed individually to each new page, instead
they are retrieved from the session we open at the beginning of each page
(session_start()).
Also notice that all session variable values are stored in the global $_SESSION
variable:
OR
Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset()
and session_destroy():
Questions?