SITERAW

Superglobal Variables, Sessions and Cookies

You've probably noticed that the arrays $_GET and $_POST are a bit unusual: their names are written in all caps and start with an underscore, but more importantly, these variables are generated automatically by PHP. These are what we call superglobal variables.

There are other types of superglobals that we'll explore in this chapter. Among them, some allow you to store information throughout a user's visit (that's the idea behind sessions), and others let you store data on a visitor's computer for several months (that's the idea behind cookies).

Superglobal Variables

Let me tell you something fun: you've already used superglobals... without even realizing it.

These "special" variables are easy to spot. Here are 3 things to help you recognize them:

  • They're written in all caps and, with one exception, start with an underscore _ (the underscore character). $_GET and $_POST are examples you already know.
  • Superglobals are arrays, because they typically contain lots of information.
  • These variables are automatically created by PHP every time a page loads. So they're available everywhere: in the middle of your code, at the start, inside functions, you name it.

To view the contents of a superglobal and see what's inside, the easiest way is to use the print_r function, since it's an array. For example:

<?php
print_r($_GET);
?>

Let's take a quick tour of the main superglobal variables that exist. We won't be using all of them, but this will give you a good overview so we can focus later on the most useful ones.

  • $_SERVER: contains values returned by the server. There are lots of them, and a few can be very useful. For instance, remember $_SERVER['REMOTE_ADDR']. It gives you the IP address of the client requesting the page. This can help identify the user.
  • $_ENV: these are environment variables, also provided by the server. You'll mostly find them on Unix servers. Generally, there's nothing especially useful here for our web projects.
  • $_SESSION: holds session variables. These are stored on the server during a user's visit. We'll learn how to use them in this chapter.
  • $_COOKIE: stores cookie values saved on the visitor's computer. This lets us save data for several months, like remembering their name.
  • $_GET: you know this one — it holds data sent through URL parameters.
  • $_POST: also familiar, it holds data sent through a form.
  • $_FILES: contains the list of files uploaded via a form.

As you can see, you already know a good number of these superglobals. Now let's dive deeper into sessions and cookies. That way, we'll have covered the main ways to pass variables from one page to another! :)

Sessions in PHP

Sessions let you store variables across every page on your website. So far, we've managed to pass variables from one page to another using the GET method (by changing the URL: page.php?variable=value) and the POST method (via a form).

But imagine you want to pass variables around across all the pages of your site during a visitor's session. GET and POST aren't ideal here since they're made to transfer information just once, from one page to another. You can send the visitor's name and surname from one page to the next, but once another page loads, that info is "forgotten." That's why sessions were invented.

How Sessions Work

How does PHP handle sessions? Here are the 3 steps you need to know:

  • A visitor arrives on your site. You ask PHP to create a session for them. PHP then generates a unique number. This number is usually very long and written in hexadecimal. For example: a03bbffc6198e6e0cc2715047bc3667f.
  • This number is the session identifier, also known as the "session ID" (or PHPSESSID). PHP automatically sends this ID from page to page using a cookie in most cases.
  • Once the session is created, you can make as many session variables as you want. For instance, you can create $_SESSION['firstName'] to hold the visitor's first name, $_SESSION['lastName'] for their surname, and so on. The server keeps these variables even after the PHP page finishes loading. That means you can retrieve this info on any page of your site using the $_SESSION superglobal!
  • When the visitor logs out, the session ends and PHP "forgets" all the session variables you created. It's actually hard to know exactly when a user leaves your site — if they close their browser or go to another site, yours doesn't get notified. Either the user clicks a "Logout" button (which you'll create), or after several minutes of inactivity they're logged out automatically (that's called a timeout). Most often, it's the timeout that logs them out.

This might sound a little complicated, but it's actually super simple to use. You only need to know two functions:

  • session_start(): starts the session system. If the visitor is new, a session ID is created for them. You must call this at the very beginning of every page where you need session variables.
  • session_destroy(): ends the visitor's session. It gets called automatically when they stop loading pages on your site for several minutes (timeout), but you can also make a "Logout" page that calls it manually.

A small warning: you must call session_start() before writing any HTML code (even before the <!DOCTYPE> tag). If you forget to call session_start(), you won't have access to the $_SESSION superglobal.

Example: Using Sessions

Here's a real-world example to show just how easy it is:

<?php
// Start the session BEFORE writing any HTML
session_start();

// Let's create a few session variables in $_SESSION $_SESSION['firstName'] = 'John'; $_SESSION['lastName'] = 'Smith'; $_SESSION['age'] = 21; ?> <!DOCTYPE> <html> <head> <title>My Page Title</title> <meta http-equiv="Content-Type" content="text/html" /> </head> <body>

<p> Hey there <?php echo $_SESSION['firstName']; ?>!<br /> You're on the homepage of my site (index.php). Want to check out another page? </p>

<p> <a href="mypage.php">Link to mypage.php</a><br /> <a href="myscript.php">Link to myscript.php</a><br /> <a href="info.php">Link to info.php</a> </p>

</body> </html>

You can create session variables anywhere in your code (not just at the beginning like I did here). What matters is that session_start() is called right at the start of the page.

As you can see, I created 3 session variables for the visitor's name, surname, and age. I also linked to other pages on my site.

And here's something important: those links are totally basic — they pass no info at all. I'm not sending the name, surname, or age anywhere. I'm not even passing the session ID. PHP takes care of everything for us.

Now, on every page of my site, I can access $_SESSION['firstName'], $_SESSION['lastName'], and $_SESSION['age']! Just remember to call session_start() on each page where you need them.

Here's an example of the source code for info.php:

<?php
session_start(); // Start the session BEFORE anything else
?>
 
<!DOCTYPE>
<html>
   <head>
       <title>My Page Title</title>
       <meta http-equiv="Content-Type" content="text/html" />
   </head>
   <body>

<p>Hey, welcome back!</p>

<p> I remember you! Your name is <?php echo $_SESSION['firstName'] . ' ' . $_SESSION['lastName']; ?>!<br /> And your age... let me think... You're <?php echo $_SESSION['age']; ?>, right? :-D </p>

</body> </html>

See? We just started the session with session_start() and displayed the session variable values.

And just like that — magic! 🧙‍ The values were all saved for us — no effort needed!

In short, you can create session variables just like regular variables, as long as you store them in the $_SESSION array and start the session with session_start(). These variables are preserved across pages for the duration of the visitor's session. :)

To manually end a visitor's session, you can create a "Logout" link that leads to a page calling session_destroy(). But remember, their session will be destroyed automatically after some inactivity.

Practical Uses of Sessions

In real life, sessions are super handy on websites (and not just for remembering someone's name). Here are a few examples:

  • Imagine a script that asks for a login and password so a visitor can log in (authenticate). You can save that info in session variables and remember their login on every page!
  • Since you remember their login, and the session variable only exists if they successfully logged in, you can use it to restrict certain pages to specific users. This lets you create a secure admin area: if the login session variable exists, show the content; if not, show an error. Sound familiar? It's just like the "password-protected page" exercise — only now you can protect multiple pages with sessions.
  • Sessions are essential on e-commerce sites. They let you manage a shopping cart: you track the products the user wants to buy, no matter what page they're on. When they finalize the order, you retrieve the info and... make them pay!

Cookies in PHP

Working with cookies is more or less like working with sessions, with just a few small differences that we'll cover. Here's what we'll do to explore cookies:

  • First, we'll see what exactly a cookie is... because let's be honest, someone out there might think I'm about to share a baking recipe! ;)
  • Then we'll learn how to write a cookie. It's easy to do, as long as you follow a few simple rules.
  • Finally, we'll look at how to read a cookie. That'll be the easiest part. ;)

What's a cookie?

A cookie is a small file saved on the visitor's computer.

This file contains text and is used to "remember" things about the visitor. For example, you might store their username in a cookie — so the next time they visit your site, you can read the cookie and greet them by name.

Cookies sometimes get a bad rap. People often mistakenly think cookies are "dangerous." But no, they're not viruses — just tiny text files that store bits of information. At worst, an e-commerce site might remember you like digital cameras and only show you ads for cameras... but that's it. These little guys are harmless for your computer.

Each cookie usually stores one piece of information. So if you want to save both the visitor's username and their birthdate, it's best to create two separate cookies.

Where are cookies stored on my hard drive?

That depends on your browser. Normally, you don't need to mess with these files directly, but you can view the list of stored cookies right from your browser. And you can delete them at any time.

Cookies are organized by website. Each site can write several cookies. Every cookie has a name and a value (which you can usually find listed under "Content" or similar). You'll also notice that like any good cookie, each one has an expiration date. Once it's expired, it's no longer "safe to eat" — your browser automatically deletes it.

So, cookies are temporary pieces of information stored on a visitor's computer. They're small — just a few kilobytes — so you can't save a ton of data, but it's usually plenty for what you need.

Writing a cookie

Just like a variable, a cookie has a name and a value. For instance, a cookie named username might have the value Jace.

To write a cookie, you use the PHP function setcookie.

It usually takes three parameters, in this order:

  • The name of the cookie (e.g., username)
  • The value of the cookie (e.g., Jace)
  • The expiration date, given as a timestamp (e.g., 1090521509)

Let's talk about that expiration date for a second. A timestamp is the number of seconds since January 1, 1970. This value increases by one every second. To get the current timestamp, use the time() function. To make a cookie expire in the future, add however many seconds you want to the current time.

If you want your cookie to expire in one year, write: time() + 365*24*3600. That's the current timestamp plus the number of seconds in a year. The result? Your cookie will expire exactly one year from now.

Here's how to create a cookie:

<?php setcookie('username', 'Jace', time() + 365*24*3600); ?>

Making your cookie more secure with httpOnly mode

I recommend enabling the httpOnly option for cookies. Without going into too much detail, this makes your cookie inaccessible to JavaScript in all browsers that support it (which includes all modern browsers). This greatly reduces the risk of XSS (Cross-Site Scripting) vulnerabilities if you ever forget to use htmlspecialchars somewhere.

So, I suggest creating your cookie like this instead:

<?php setcookie('username', 'Jace', time() + 365*24*3600, null, null, false, true); ?>

That last parameter — true — enables httpOnly mode, making the cookie more secure. It's free, easy, and helps prevent visitors from having their cookies stolen via XSS exploits.

The parameters in the middle are ones we're not using here, so we just pass null.

Create the cookie before writing any HTML

There's one little gotcha with setcookie... just like session_start, this function only works if you call it before any HTML output (i.e., before the <!DOCTYPE> tag).

So NEVER write any HTML before calling setcookie. Most people who run into problems with cookies have made this exact mistake — so don't forget!

Now let's see how to write two cookies: one that stores my username for a year, and another that stores my country:

<?php
setcookie('username', 'Jace', time() + 365*24*3600, null, null, false, true); // First cookie
setcookie('country', 'Australia', time() + 365*24*3600, null, null, false, true); // Second cookie...

// ONLY AFTER THIS POINT can we start writing HTML ?>

<!DOCTYPE> <html> <head> <!-- content --> </head> <body> <!-- content --> </body> </html>

And there you go, cookies written! :D As you can see, to write two cookies, you simply call setcookie twice.

Displaying a cookie

This is the easiest part. Before PHP starts processing a page, it reads all the cookies sent by the client and loads their data. This data is stored in the superglobal $_COOKIE, in array form as usual.

So, if I want to get the visitor's username from their cookie, all I have to do is write: $_COOKIE['username'].

Which gives us a simple PHP snippet to display their username and country:

<p>
    Hey! I remember you!<br />
    Your name is <?php echo $_COOKIE['username']; ?> and you're from <?php echo $_COOKIE['country']; ?>, right?
</p>

Once again, the big advantage here is that superglobals are accessible everywhere.

Need to check the contents of the username cookie? Just look at $_COOKIE['username']! :D

Keep in mind: if the cookie doesn't exist, then the superglobal variable won't exist either. So you should always check with isset() to see if a cookie is set before using it.

Cookies come from the visitor. And like anything that comes from the user, they're not safe by default. Any visitor can create or modify their own cookies and send false info to your site. So when reading cookies, always remember: they may have been tampered with. Don't blindly trust cookie data!

Modifying an existing cookie

You might be wondering how to update a cookie that's already been set. Super easy: just call setcookie again with the same cookie name. This will overwrite the old one.

For example, if I now live in Japan, I'd write:

<?php setcookie('country', 'Japan', time() + 365*24*3600, null, null, false, true); ?>

Note that this also resets the cookie's expiration date to one year from now.

More on cookies and sessions

Did you know... sessions are actually cookies?

Didn't see that coming, did you? I hinted at it in the beginning.

Yes — sessions are really just special cookies.

  • Thanks to cryptography, their real values are hidden from the user (they can't just switch from a normal session to an admin one).
  • The data is stored server-side, linked to a unique session ID.
  • Sessions are mainly used to store sensitive information (you don't want the user fiddling with it).

The special cookie used by sessions is usually called a "session cookie." It stores only the identifier — and that's what's sent to the client.

So... when should I use a session, and when a cookie?

It depends on what kind of data you want to store. If you're saving a username for a social network as a cookie, that's a terrible idea... the user could just edit it to say "Elon Musk" and suddenly become your site's mega-admin! Not good.

On the other hand, if the user picks "dark mode" instead of "light mode," you don't need to go overboard with a session — a simple cookie will do just fine.

Now you know everything you need about superglobals! With cookies and sessions, you've got two powerful tools for saving info from page to page.

How to Build a Website in HTML and CSS

Enjoyed this PHP & MySQL course?

If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.

More information