How do i access my cookies in PHP and Jquery?
So, being 7+ months pregnant gives you some weird cravings... Like cookie brownies. Not a cookie and a brownie, they needed to be baked together (very important). Anyways, probably not what you came to read – it did spark the idea to write about cookies tho.
One fun thing about cookies is that you can set them in jQuery and read them in php. Alternatively you can set them in PHP and read them in jQuery.
This can be useful when you want to set cookies with jQuery as a result of a user action, and then want to remember the cookie to use it in PHP on page load to display different content – like an age gate limiting access to the site.
So like this situation:
- you want to show an age gate if there is no cookie set
- the user interacts with the site and the cookie is set with jQuery
- you can use that same cookie later in PHP to avoid showing the age gate again.
This is a more seamless experience than just using jQuery, because you don't need the page to load to know if you want to show the age gate or not.
PHP
Read more how to set cookie here
To delete a cookie, you can't really do that. But you can unset the value and then set the cookie to have an empty value and be expired. It will be a dead cookie the next time the page loads.
<?php
/* set a cookie */
setcookie('age_gate', 'true', 86400, '/');
/* read a cookie */
$cookie = isset($_COOKIE["age_gate"])?$_COOKIE["age_gate"]:null;
/* delete a cookie */
unset($_COOKIE['age_gate']);
setcookie('age_gate', '', time() - 3600, '/'); // empty value and old timestamp
?>
jQuery
For jQuery, i like to use the cookie library available here
(it's a simple, lightweight JavaScript API for handling cookies)
//set a cookie
Cookies.set('age_gate', 'true', { expires:86400, path: '/' }); // 86400 seconds in day
//read a cookie
Cookies.get('age_gate');
//delete a cookie
Cookies.remove('age_gate', { path: '/' });
So basically if jQuery is a cookie and PHP is a brownie, you should be able to have them work together when the need arises to keep track of your user session in glorious harmony.