Chapter 5 - Cookies and Sessions

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Chapter 5: Cookies and Sessions

Describe the Stateless Model


A Stateless application or process is something that does not save or reference information about
previous operations. Every time it carries each operation from the scratch just like the first time
and provides functionality to use print, CDN (Content Delivery Network) or the Web Servers in
order to process every short-term request. For example, someone is searching a question in the
search engine and pressed the Enter button. In case if the searching operation gets interrupted or
closed due to some reason, you have to start a new one as there is no saved data for your
previous request.
In the pure form of the stateless model, a client program makes a request to an application server,
which sends data back to the client. The server treats all client connections equally and saves no
information from prior requests or sessions. A website that serves up a simple static web page is
a good example of the stateless model.

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.

Create and Read Data from sessions


As web applications have matured, the need for statefulness has become a common
requirement. Stateful web applications, meaning applications that keep track of a particular
visitor’s information as he travels throughout a site, are now so common that
they are taken for granted.
Given the prevalence of web applications that keep track of things for their visitors—
such as shopping carts, online banking, personalized home page portals, and social
networking community sites—it is hard to imagine the Internet we use every day without stateful
applications.

What Is a Session in PHP?


A session is a mechanism to persist information across different web pages to identify users as
they navigate a site or app.

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.

The following diagram depicts the HTTP protocol in a nutshell.

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.

How to Start a Session


Whenever you want to deal with session variables, you need to make sure that a session is
already started. There are a couple of ways you can start a session in PHP.

Use the  session_start  Function

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.

Automatically Start a Session


If there’s a need to use sessions throughout your application, you can also opt in to starting a
session automatically without using the  session_start  function.

There’s a configuration option in the php.ini file which allows you to start a session


automatically for every request— session.auto_start . By default, it’s set to  0 , and you can set it
to  1  to enable the auto startup functionality.

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.

How to Get a Session Id?


the server creates a unique number for every new session. If you want to get a session id, you can
use the  session_id  function, as shown in the following snippet.

<?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.

How to Create Session Variables?


once a session is started, the  $_SESSION  super-global array is initialized with the
corresponding session information. By default, it’s initialized with a blank array, and you can
store more information by using a key-value pair.

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.

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we will access the session
information we set on the first page ("demo_session1.php").

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>

How to Modify and Delete Session Variables


You can modify or delete session variables created earlier in the application in the same way as
for regular PHP variables.
<?php
session_start();
  
if (!isset($_SESSION['count']))
{
  $_SESSION['count'] = 1;
}
else
{
  ++$_SESSION['count'];
}
  
echo $_SESSION['count'];
?>

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.

How to Destroy a Session


the  unset  function, which is used if you want to delete specific session variables. On the other
hand, if you want to delete all session-related data at once, you can use
the  session_destroy  function.

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();

// destroy the session


session_destroy();
?>

</body>
</html>

Why and when to use Sessions?

 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,

1) A user requests for a page that stores cookies

2) The server sets the cookie on the user’s computer

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.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.


Argument Usage
name Required. The name the cookie will be referred to. Must be a string.
value Optional. The value of the cookie.
expiration Optional. If an expiration time is not set, the cookie will expire when the browser
is closed.
path Optional. The path on the server the cookie will be available on. The cookie can
be set to '/' to be available to the entire domain.
domain Optional. The (sub)domain that the cookie is available to. Sub-domains of the
specified domain are automatically included.
secure Optional. If set to true, the cookie will only be set for a HTTPS secure
connection.

PHP Create/Retrieve a Cookie

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

To modify a cookie, just set (again) the cookie using the setcookie() function:

<?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

To delete a cookie, use the setcookie() function with an expiration date in the past:

<?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>

Why and when to use Cookies?

 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

You might also like