$_COOKIE

Last updated on

Ever notice how some websites just seem to "know" you? That’s thanks to cookies! When you’re working with PHP, $_COOKIE becomes a handy way to make your site feel a bit more personal. Let's dive into how it works, how you can set it up, and why it makes such a difference.

Think of $_COOKIE as your way of helping PHP remember things about users between visits. Whether it’s holding onto their login info or saving their preferences, cookies are like little notes stored in their browser, ready for the next visit. This makes it easier for users to pick up right where they left off, like a welcome back from a friend.

In the following section, you will learn how to set and retrieve cookies using PHP, so that you can apply your knowledge.

Setting Cookies in PHP

Setting up a cookie in PHP is quick—just one line, and you’re set. Here’s an example that creates a cookie named user_name:  

setcookie("username", "JohnDoe", time() + (86400 * 30), "/");

This code snippet sets a cookie with user_name as “JohnDoe,” which will hang around for an hour. When the user comes back within that time, PHP can read it and greet them like an old friend.  

The next section shows you how to retrieve and use set cookies, enabling your application to utilize stored data.

When a user returns, here’s how you can check if that user_name cookie is still around: 

if (isset($_COOKIE["user_name"])) {
    echo "Welcome back, " . $_COOKIE["user_name"];
} else {
    echo "Hello, new visitor!";
}

Using isset() here is key. It makes sure PHP only tries to read the cookie if it’s actually there. That way, you avoid any errors if the cookie has expired or been cleared.  

In the following section, we will continue with ways of updating and deleting cookies to widen our horizons for managing sessions.

Updating and Deleting Cookies

Changing a cookie is simple because you just set it with the same name but with the new value, kind of like replacing one cookie with another with some different information:

setcookie("username", "JaneDoe", time() + (86400 * 30), "/");

There will be times when you want to clear out a cookie—like when a user logs out. To delete a cookie, set its expiration time in the past:

setcookie("user_name", "", time() - 3600); // Expired an hour ago

Once the user reloads, that cookie will disappear. It’s an easy way to tidy up and keep only what’s necessary.

The following section will give you an overview of the best practices for security that you should follow when working with cookies in PHP to keep your users safe.

While cookies are useful, they’re not always private. Here are a few tips to make sure they’re as safe as possible:

  • Use HTTPS: This encrypts cookies when they’re sent to your server, keeping them safe from snooping.
  • Set HttpOnly: Adding this flag keeps JavaScript from accessing the cookie, which helps prevent certain types of attacks.
  • Use the secure flag: This makes sure cookies are only sent over HTTPS, adding another layer of security.

Here’s an example with security settings:

setcookie("user_name", "JohnDoe", time() + 3600, "/", "", true, true);

This line sets up a secure cookie that’s only accessible over HTTPS and not available to JavaScript.

It’s good to remember that cookies are meant for small bits of data. Browsers generally limit them to about 4KB, so save only the essentials. If you need to store a lot, consider using other storage methods like sessions or databases.

Wrapping Up

PHP $_COOKIE lets you create a more personalized experience, whether that means keeping users logged in, saving preferences, or making content recommendations. It’s one of those small details that adds up, making your site a place people want to return to.  

To see more PHP tutorials, click here.  

Frequently Asked Questions (FAQs)

  • What is PHP $_COOKIE used for?

    The $_COOKIE superglobal in PHP is an associative array that holds all cookies sent by the browser to the server. It's commonly used to store and retrieve client-side data, like user preferences, across different sessions.
  • How do you set a cookie in PHP?

    To set a cookie, use the setcookie() function. Here's an example:
    setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); 
    This code sets a cookie named username with a value of JohnDoe, lasting for 30 days.
  • How can I retrieve a cookie value in PHP?

    You can retrieve a cookie’s value by accessing $_COOKIE with the cookie's name as the key:
    if(isset($_COOKIE["username"])) {
        echo "Welcome back, " . $_COOKIE["username"];
    } 
    This checks if the username cookie exists before displaying its value.
  • How do you delete a cookie in PHP?

    To delete a cookie, set its expiration time to a past date:
    setcookie("username", "", time() - 3600, "/"); 
    This makes the browser delete the username cookie by setting its expiration to an hour ago.
  • What are best practices for securing cookies in PHP?

    To secure cookies, consider these flags in setcookie():
    - HttpOnly prevents JavaScript from accessing cookies.
    - Secure ensures cookies are only sent over HTTPS.
    - SameSite reduces the risk of CSRF attacks.
    Here's how you’d apply these security flags:
    setcookie("username", "JohnDoe", time() + (86400 * 30), "/", "", true, true); 
    This sets HttpOnly and Secure to protect your cookie.
  • Can you store sensitive data in cookies?

    No, it's not recommended to store sensitive data in cookies, as they are stored client-side and can be accessed by others. For sensitive information, use server-side sessions instead.
  • What’s the difference between cookies and PHP sessions?

    Cookies store data client-side and can persist between browser sessions, while PHP sessions store data server-side and offer a more secure option for managing sensitive information.
Share on: