Cookies

Cookies remember user preferences and login status

I’m starting to run out of topics to write about so this might be my last one on PHP before I transition to Laravel. Exciting and sad at the same time. Once you get past this topic, anything else that you want to learn PHP related is going to be pretty trivial. Have fun exploring additional features, finding unique ways to code, standardizing your code, and progressing into frameworks.

https://blog.devgenius.io/php-p94-sessions-23e106ad374f

What is a Cookie?

A cookie is small text-file with user identifiable information that’s set on the user’s computer by the server. The cookie is sent to the server each time that a new request comes from the user. So, each time that a user visits a different page on the website, the request is sent and so is the cookie.

You’ve seen examples when a user is kept logged into a web-application. How do they do it? With cookies. A user identifier is encrypted, and often salted, and stored in the database and the user’s browser. When they return to the website, the cookie is sent and the user is automatically logged in. That’s a little beyond the scope of this article, but if you’re interested in learning more, look up Authentication and Long Term Persistence with PHP Cookies. Here’s a good article on it.

https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence?source=post_page—–8c87c1c74b8d——————————–

It’s such a simple concept and yet so mysterious to new developers. Let’s look at an example and see what we can do.

Setting a Cookie

Remember when I said that the server sets the cookie on the user’s machine. Well, how does it do that? With the…drum roll…setcookie function. That’s right, the function is called setcookie.

The setcookie function is part of the HTTP header so it must be called before the page is rendered and sent to the client.

setcookie(
    string $name,
    string $value = "",
    int $expires_or_options = 0,
    string $path = "",
    string $domain = "",
    bool $secure = false,
    bool $httponly = false
): bool

The first three arguments are the ones that we’re interested in. The $name is the name of the cookie. The $value is the value of the cookie. And the $expires_or_options is the time it takes to expire. It takes a unix timestamp, so for example, time(). If we want the cookie to expire in 1 hour, we need to add 3600 seconds to the time()time() + (60 * 60). What if we wanted for the cookie to expire in 24 hours? time() + (60 * 60 * 24). What about 1 week from today? time() + (60 * 60 * 24 * 7). What about 30 days from now? time() + (60 * 60 * 24 * 30). Pretty simple right?

Time to look at the code for set_cookie.php.

<?php
setcookie(
    "full_name",
    "Dino Cajic",
    time() + (60 * 60 * 24 * 30)
);

Cool. Can we see it? Of course we can. Right click anywhere on the page and click Inspect Element. Go to Application -> Storage -> Cookies. You should see the full_name cookie and the value set.

Pretty cool. How do we retrieve it now?

Retrieving a Cookie

How do we get the cookie from the user? That’s automatically sent to the server by the user’s browser. The cookie is stored in the $_COOKIE superglobal. Let’s see what the output is once we dump it.

<?php
var_dump($_COOKIE);

The output of the command is:

/app/93 Cookies/view_cookie.php:3:
array (size=1)
  'full_name' => string 'Dino Cajic' (length=10)

It’s just an associative array. Let’s display the full_name back to the user. We’ll check to see if the full_name key is set, and if it is echo out the user’s full name.

<?php // view_cookie.php

if ( isset($_COOKIE["full_name"]) ) {
    echo "Hello " . $_COOKIE["full_name"];
} else {
    echo "Cookie not set.";
}

Can the data be modified? Of course. In the console, I’ll make the change from Dino Cajic to Frank Beefy.

Once you refresh the page, the new output will be Hello Frank Beefy. Can we also inject cookie data? Yes we can, so be careful.

If we var_dump the $_COOKIE, we’ll get the following.

/app/93 Cookies/view_cookie.php:3:
array (size=2)
  'full_name' => string 'Frank Beefy' (length=11)
  'something_random' => string 'Something I injected' (length=20)

The server did nothing to set the cookie. The user set this cookie on their own by right clicking inside of the console and adding the something_random cookie for that domain.

How to Delete a Cookie?

You just set it, but with a time in the past. For example, time() - (60 * 60). This will set a cookie 1 hour in the past, making it obsolete.

<?php // delete_cookie.php
setcookie(
    "full_name",
    "",
    time() - (60 * 60)
);

You’ll need to pass some data as the second argument since you can’t skip it. An empty string works.

Before running the script, open your console and watch it disappear as you load your delete_cookie.php page.

And there you go, cookies. Straightforward like everything else. Sometimes you just need to have some isolated examples and a little bit of high-level understanding about what is happening.

Sessions

SESSIONS ENABLE PERSONALIZED AND STATEFUL EXPERIENCES

PHP – P94: SESSIONS

What is a session? It’s a way to store data on the server without using the database. When a user goes from page to page, each request generates a new set of variables that will be used to help generate the pages that the user needs to see.

Cookies

Cookies remember user preferences and login status

PHP – P95: cookies

A cookie is small text-file with user identifiable information that’s set on the user’s computer by the server. The cookie is sent to the server each time that a new request comes from the user.

MySQL Primary Foreign Keys

PRIMARY AND FOREIGN KEYS: THE BACKBONE OF RELATIONAL DATABASES

PHP – P96: MYSQL PRIMARY AND FOREIGN KEYS

Primary keys uniquely identify records in a table. Foreign keys establish relationships between tables. They ensure data integrity and enforce uniqueness.

Leave a Reply