Professional Documents
Culture Documents
Chapter 5 - Cookies and Sessions
Chapter 5 - Cookies and Sessions
Chapter 5 - Cookies and Sessions
Stateful Model
When an application operates in a stateful mode, the server keeps track of who users are and
what they do from one screen to the next. Preserving the state of users’ actions is fundamental
to having a meaningful, continuous session. It typically begins with a login with user ID and
password, establishing a beginning state to the session. As a user navigates through the site,
the state may change. The server maintains the state of the user’s information throughout the
session until logout.
The HTTP protocol is stateless, which means that HTTP has no built-in way to keep track of a
user as they navigate from one webpage to another. As a result, there are a number of other
methods used to maintain state. These include session state, cookies, hidden form, passing
variables through the query string, and form posts.
A Stateful application remembers specific details of a user like profile, preferences, and user
actions. This information is considered as the ‘Status’ of a system. For example, your shopping
cart while using any website in Cloud. Each time you select an item and add it in your cart, you
add it with the items added previously and eventually, you navigate to the checkout page.
The HTTP protocol is a stateless protocol, which means that there's no way a server can
remember a specific user between multiple requests. For example, when you access a web page,
the server is just responsible for providing the contents of the requested page. So when you
access other pages of the same website, the web server interprets each and every request
separately, as if they were unrelated to one another. There's no way for the server to know that
each request originated from the same user.
In this model, if you wanted to display user-specific information, you'd have to authenticate a
user in each request. Imagine if you had to type your username and password on every page that
displayed your profile information! Yes, it would be cumbersome and not practical at all, and
that's where sessions come into the picture.
A session allows you to share information across different pages of a single site or app—thus it
helps maintain state. This lets the server know that all requests originate from the same user, thus
allowing the site to display user-specific information and preferences.
The following diagram depicts how the HTTP protocol works with sessions.
This is the method that you'll see most often, where a session is started by
the session_start function.
<?php
// start a session
session_start();
// manipulate session variables
?>
The important thing is that the session_start function must be called at the beginning of the
script, before any output is sent to the browser. Otherwise, you’ll encounter the
infamous Headers are already sent error.
session.auto_start = 1
On the other hand, if you don’t have access to the php.ini file, and you're using the Apache web
server, you could also set this variable using the .htaccess file.
php_value session.auto_start 1
If you add the above line in the .htaccess file, that should start a session automatically in your
PHP application.
<?php
session_start();
echo session_id();
?>
That should give you the current session id. The session_id function is interesting in that it can
also take one argument—a session id. If you want to replace the system-generated session id
with your own, you can supply it to the first argument of the session_id function.
<?php
session_id(YOUR_SESSION_ID);
session_start();
?>
It’s important to note that the session_id function must be placed before the session_start call
when you want to start a session with a custom session id.
Let’s go through the following example script that demonstrates how to initialize session
variables.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session
and set some session variables:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before any HTML
tags.
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:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Another way to show all the session variable values for a user session is to run the following code:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
On the other hand, if you would like to delete a session variable, you can use
the unset function,
<?php
// start a session
session_start();
// initialize a session variable
$_SESSION['logged_in_user_id'] = '1';
// unset a session variable
unset($_SESSION['logged_in_user_id']);
?>
Thus, you can no longer access the $_SESSION[‘logged_in_user_id’] variable as it’s deleted
by the unset function. So that’s how you can alter the session information.
The session_destroy function deletes everything that’s stored in the current session. Having
said that, it doesn't unset global variables associated with the session or unset the session cookie.
So if you're using the session_destroy function to log a user out, you must unset
the $_SESSION variable and unset the session cookie as well.
To remove all global session variables and destroy the session,
use session_unset() and session_destroy()
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
You want to pass values from one page to another.
You want the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to
passing them in the URL
You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
What Is a Cookie?
An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a
small piece of data stored on the user's computer by the web browser while browsing a website.
A cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer.
Once a cookie has been set, all page requests that follow return the cookie name and value.
Here,
3) Other page requests from the user will return the cookie name and value
We can think of cookies as text files, which are saved to your computer. When you request any
web page, a web server sends the response of that web page to your browser. Along with the
response, a web server could also send Set-Cookie HTTP headers that request your browser to
create cookie files on your computer. Once cookies are created for a website, a web server can
subsequently read and write content from and to these files.
Cookies have an expiration date along with the cookie data. This date is set so that a browser can
delete old cookies when they are no longer needed by a web server. If the expiration date is
empty, the cookie will be deleted when the connection with the server is closed. This occurs
when the user closes the site's window or tab, or when the user closes the entire browser. These
cookies, sometimes called session cookies, are mostly used for storing temporary settings.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
The following example creates a cookie named "user" with the value "John Doe". 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:
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
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];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Modify a Cookie Value
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<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];
}
?>
</body>
</html>
Delete a Cookie
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Check if Cookies are Enabled
The following example creates a small script that checks whether cookies are enabled. First, try to
create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Http is a stateless protocol; cookies allow us to track the state of the application using
small files stored on the user’s computer. The path where the cookies are stored depends
on the browser.
Personalizing the user experience – this is achieved by allowing users to select their
preferences. The page requested that follow is personalized based on the set preferences
in the cookies.
Tracking the pages visited by a user
References
https://www.w3schools.com/php/php_cookies.asp
https://code.tutsplus.com/tutorials/how-to-use-sessions-and-session-variables-in-php--cms-31839
https://code.tutsplus.com/tutorials/how-to-work-with-cookies-in-php--cms-36575
https://www.guru99.com/cookies-and-sessions.html
PHP COOKBOOK By David Sklar and Adam Tracbtenberg page 333-Textbook