PHP Cookie, Raw Cookie and How to Cookie with Caching System

For years I thought I understood “cookie” very well. Especially when I figured out it’s a great way to share data between JavaScript and PHP. I always got results as I expected in many projects with this approach.

“Why not just saving the values to database and just use PHP to access it?” you might be asking. Most of the cases are because we need to access such values in JavaScript. For example, we have an eCommerce website and we let the user chooses her location with a lightbox window. The lightbox should only appear once and after the user makes the choice, it just goes away.

Since we use JavaScript to control the presence of the lightbox, we save the location into a cookie and detect if the cookie exists to show the lightbox. We often also save the value into the database when the user logged in. But if she doesn’t log in, we can only depend on this very cookie in the browser.

In such scenario, we also use PHP to check the cookie value and change the product prices accordingly. If you set a cookie with setcookie function in PHP, but can’t get the value in JavaScript, try to set it for the entire domain. That should help.

Have you heard about raw cookie?

No, I haven’t. …Until a week ago. The project I was working on got into a weird problem with cookies. And that led me to a new concept called “raw cookie”.

In short, I used a cookie to save the email address which users input in the lightbox form. It worked fine with normal email addresses. But with the “labeled” email from Gmail, like in this format [email protected], I started to get into trouble.

I used PHP variable $_COOKIE['email'] to get the email. When it’s labeled, I always got something like 1fixdotio [email protected] in return. The plus sign just disappeared with a blank space left. It only happened when I got the cookie with PHP. If I used JavaScript, the plus sign was just fine and I can also saw the right value from my browser’s cookie storage.

I found a thread from Stack Overflow mentioned “raw cookie” in PHP. Values in raw cookies aren’t “urlencoded“. With setrawcookie function in PHP, it seems to work out my problem. But unfortunately, I have to set the cookie with JavaScript and such function doesn’t exist.

Luckily I found another thread on Stack Overflow, which was a real lifesaver this time. The following piece of code shows you how to get raw cookie in PHP:

With such method, I can now get the right value from the cookie with the plus sign. If you do find this help, please upvoted the thread on SO! (Let’s make it a warm place where we’d like to send our kids to ;))

The PHP cookie unfriendly caching system

Cached pages can be loaded way faster. Why? Because the server-side technique (Nginx or Apache modules) pre-saves PHP pages as static HTML files. When visitors come, the browser just loads the static files physically store on the server and get updated periodically.

Technically it doesn’t mean you cannot access the value of PHP cookies in a hosting environment with page caching mechanism. The thing is, the reason we use cookies is often to change a certain part of the content on the page. For example, to show the username or currency, country etc.

Now imagine in such server environment, if we use PHP cookie to display the username on the top right corner of the website, it actually introduces problems. Only because the first person came to the site is called “John”, the top right corner will be showing “Welcome! John!” to every later comer.

Typically there are two approaches to solve this problem. First, we can exclude such cookie from the caching system. So when the cookie gets generated, the page caching stops working right away. The server falls back to generate dynamic page content with PHP.

E-Commerce WordPress websites often adopt the first approach. If you ever had similar problems, this great post from Rahul Bansal would be a start for you to solve yours. Since It requires you edit your server configuration, it’s not ideal if you’re just a general WP theme or plugin developer. (Or you just don’t have the right permission.)

It’s time for AJAX to weight in

The second approach is we depend on the AJAX friendly nature of WordPress. The AJAX way means we can have a PHP function to access cookie and generate data we want, then using JavaScript to get the results and change the DOM. You can check out the following article from WPShout for a functional demo on how to use cookies with a full page caching WordPress.

I personally recommend the second approach because it obvious outperforms the first one. You can still have your pages cached that provides better user experience. But keep in mind, if more content on the page needs to be dynamic, you won’t be able to take too much advantage from it.

What about page fragment caching?

I’ve written a post on page fragment caching with W3 Total Cache a while back ago. I didn’t try but maybe with the same method, you can use PHP cookie with page caching if you use W3 Total Cache.

But with other server side caching mechanisms, like Varnish or Redis, I have no experience and have no clue how they work. If you have related experience, feel free to share your findings in the comments.

2 responses

  1. Can’t say thank you enough – can’t tell you how long I’ve had the most vague knowledge of cookies and caching, pulling out my hair working with cookies or php sessions and not understanding why it worked sometimes and didn’t work at other times.

    1. Yoren Chang Avatar
      Yoren Chang

      Hey Luyen! You’re the most welcome. I documented this because I’ve had the same painful experience myself, glad it can be of use to you.

Leave a Reply

Your email address will not be published. Required fields are marked *