Cookies are all around in our everyday life while we browse the Internet. Most people wouldn't know much about them, if not for those "our website uses cookies to be operational" signs that are on mostly any page now since GDPR. Cookies have a long history if sometimes being good, sometimes bad. As it is usual with most aspects of the world, this technology can be used in a good or bad way.

In this tutorial we will explore cookies a bit from the server side programming perspective: we'll create an example cookie in PHP, and store the visitor's chosen username in it. The cookie will reside in the browser of the visitor, so on the next visit we can read it and use it to greet the visitor on the username submitted. Our simple webpage will recognize the visitor as long as the cookie is present in the browser. We do not store any information on the server side: if the visitor first checks in from a PC, and next time from a smartphone, we will not know it is the same individual. This is one of the main point with cookies: we can only identify the given client, and only as long as the data is provided by that particular browser.

In this tutorial you will learn:
  • How to setup the test environment
  • How to write a simple example program that uses cookies
  • How to test the workings of the program
  • How to reset the environment
Using cookies in PHP
Using cookies in PHP.

Software Requirements and Conventions Used

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Ubuntu 20.04 LTS
Software PHP 7.2, Firefox 74.0
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # - requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ - requires given linux commands to be executed as a regular non-privileged user

The setup

Our test environment consists of an Apache Webserver, with PHP module loaded. In our setup we use Ubuntu 20.04 LTS, but any recent distribution would do. On Ubuntu, all we need is apache2 and php:

$sudo apt-get install apache2
$sudo apt-get install php

We also need the webserver to run in order to reach our example page with a browser:

$sudo systemctl restart apache2

We'll also need a recent browser with cookies enabled. This tutorial uses latest Firefox; if you have extensions like Noscript, disable it or enable cookies from the test webserver while you are testing.


SUBSCRIBE TO NEWSLETTER
Subscribe to Linux Career NEWSLETTER and receive latest Linux news, jobs, career advice and tutorials.


The code

Consider the source code of our example PHP page as the following:

<?php
$cookie_name = "username";
$ask_to_store = false;
$username = "Unknown Visitor";

if (!isset($_COOKIE[$cookie_name])) {
        if (!isset($_REQUEST['uname'])) {
                $ask_to_store = true;
        } else {
                $username = $_REQUEST['uname'];
                setcookie($cookie_name, $username);
        }
} else {
        $username = $_COOKIE[$cookie_name];
}

echo "<html>\n<body>\n";
echo "<h1>Welcome, " . $username . "!</h1>\n";
if ($ask_to_store) {
        echo "<p>If you would like to set the username so we can greet you by that, enter it to the below form, and submit your request.</p>\n";
        echo "<form method=\"post\">\n";
        echo "<input type=\"text\" name=\"uname\"/>\n";
        echo "<input type=\"submit\"/>\n";
        echo "</form>\n";
} else {
        echo "<p>We are happy we can greet you by name.</p>\n";
}
?>
</body>
</html>

We put this code into a file called page_with_cookies.php, and place it on our test webserver's php directory. So we will be able to reach it from a browser specifying the URL as follows: http://<webserver's address>/php/page_with_cookies.php. We'll see what this code does in the following steps.

Understanding how the webpage works

Our next step is checking if our page is loading correctly. We point our browser to the page, and a simple form appears. 192.168.1.2 is the IP address of the webserver in the test environment, if you are following, you should change it to the address or DNS name of the server you put this code on.

On first visit, the page will not know who we are, so it will greet us as "Unknown Visitor". We specified this name at the code section, line 4, and because no cookie is present in the browser yet, the variable's value is not overwritten by the actual username. We detect there is no cookie set at line 6, and also that it is not a request that holds the actual username that is submitted by the visitor (line 7). This is the state where we display the form that allows the visitor to submit a username. This is specified by the Boolean variable at line 8.

Now we can fill out the input field provided in a form (generated by the code line 16-21). We'll use "Foo Bar" in this example.

Filling out the form on the page
Filling out the form on the page.

On hitting submit, the page greets by the username we sent.

Username recognized by the page
Username recognized by the page.

This isn't magic so far, we have read the data sent in the POST request, set the username accordingly, and used it to greet the visitor. But we also set a cookie (line 11) in place, which stores the data given in the browser. If we open the page again (which is another request, where we did not post any username information), we will be also greeted by the username set earlier, as long as the cookie stays in the browser. The form that enables submitting a username is also not shown on the new page, because we are the "false" branch of the if statement at line 16.



How to reset the environment

To clear the browser's state we can drop the cookie from it. In Firefox 74.0 it can be found at Preferences -> Privacy & Security -> Cookies and Site Data -> Manage Data...

Clearing cookie of the site in Firefox
Clearing cookie of the site in Firefox.

On the printscreen we search for the IP address of the testing webserver, because we reached the site by IP address. By hitting "remove selected", than "save changes" we finalize the deletion of the cookie the site placed in our browser.

If we visit the page again, the original anonymous greeting will wait us, with the form to submit a username. The site did not store any data, and without the cookie it does not know who we are.

Conclusion

This tutorial intended to give an understanding on how cookies work. We can store information with them in the visitor's browser to identify the given instance of the client who browses our site. Setting them is simple, however there are many limitations to consider: if the user clears the cookies, or not accept them at all, the functionality based on them will break. The other main thing to keep in mind that the cookie is tied to the browser instance, so if the same user opens another browser on the same computer, say Chrome, cookies that where placed in Firefox will not be seen.

FIND LATEST LINUX JOBS on LinuxCareers.com
Submit your RESUME, create a JOB ALERT or subscribe to RSS feed.
LINUX CAREER NEWSLETTER
Subscribe to NEWSLETTER and receive latest news, jobs, career advice and tutorials.
DO YOU NEED ADDITIONAL HELP?
Get extra help by visiting our LINUX FORUM or simply use comments below.

You may also be interested in:



Comments and Discussions