PHP Cookies Explained: What They Are and How to Create Them Easily
Cookies in PHP: A Beginner-Friendly Guide
What Are Cookies in PHP?
Cookies are small text files saved in the browser. They store user information for a limited time. For example:
- A cookie can remember your login for the next time you visit.
- It can save the items you add to your cart in an online store.
- It can track your preferences like language or theme.
In PHP, cookies are handled with the setcookie() function.
How to Create Cookies
The basic syntax is:
setcookie(name, value, expire, path, domain, secure, httponly);
- name – The name of the cookie.
- value – The data stored inside the cookie.
- expire – Time (in seconds) after which the cookie will expire.
- path – The path where the cookie is available.
- domain – The domain where the cookie works.
- secure – If true, cookie works only with HTTPS.
- httponly – If true, cookie is accessible only through HTTP, not JavaScript.
Example: Creating a Cookie
<?php
setcookie("username", "Azad", time() + (86400 * 7), "/");
?>
This will create a cookie named username with the value Azad. It will last for 7 days.
How to Retrieve Cookies
To get the value of a cookie, use the $_COOKIE superglobal array:
<?php
echo $_COOKIE["username"];
?>
This will show the value stored in the cookie.
How to Delete a Cookie
Deleting a cookie is simple. Just set the expiry time in the past:
<?php
setcookie("username", "", time() - 3600, "/");
?>
This will remove the cookie.
Why Use Cookies in PHP?
- User Experience – They make websites more user-friendly.
- Personalization – Websites can show content based on saved preferences.
- Sessions – Useful in login systems and shopping carts.
Note: Never store sensitive data like passwords in cookies.
Best Practices for Cookies in PHP
- Use cookies only when needed – Don’t overload users’ browsers.
- Set expiry wisely – Short expiry for better security.
- Use
httponlyandsecureflags – Prevent security risks. - Respect privacy – Inform users about cookies (GDPR compliance).
Final Thoughts
Cookies in PHP are a simple yet powerful way to store information about users. With just a few lines of code, you can create, read, and delete cookies. They make your website smarter and improve user experience. But always use them responsibly and securely.
