Professional Documents
Culture Documents
Welcome To Cosc 3101/ Internet Programming: Five Cookies and Session Management in PHP
Welcome To Cosc 3101/ Internet Programming: Five Cookies and Session Management in PHP
Chapter Five
Cookies and Session
Management in PHP
• path
– Sets the path to which the cookie applies.
– The cookie is only visible to all the pages in that directory and
its sub-directories.
– If set to '/', the cookie will be available within the entire
domain.
– If set to '/foo/', the cookie will only be available within the
/foo/ directory and all sub-directories such as /foo/bar/ of
domain .
– The default value is the current directory that the cookie is
being set in.
• secure
– Indicates that the cookie should only be transmitted over a
secure HTTPS connection from the client. When set to TRUE,
the cookie will only be set if a secure connection exists. The
default is FALSE.
• httponly
– When TRUE the cookie will be made accessible only through the
HTTP protocol. By: Fiseha B.(Msc), Dec 2014,Dilla
6
University
PHP Create/Retrieve a Cookie
• The following example creates a cookie named "user"
with the value “Tola Jira".
• 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:
• Note: The setcookie() function must appear BEFORE
the <html> tag.
By: Fiseha B.(Msc), Dec 2014,Dilla
7
University
Example
<?php
$cookie_name = "user";
$cookie_value = “Tola Jira”;
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!";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>