Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are the differences between JavaScript and PHP cookies?
Cookies are text files stored on the client's browser to remember user information across web pages. Both JavaScript and PHP can work with cookies, but they operate differently − JavaScript handles cookies on the client-side while PHP manages them on the server-side.
JavaScript Cookies
JavaScript cookies are manipulated directly in the browser using the document.cookie property. They're ideal for client-side data storage and immediate user interactions.
Setting a Cookie with JavaScript
// Set a cookie that expires in 7 days document.cookie = "username=john; expires=" + new Date(Date.now() + 7*24*60*60*1000).toUTCString() + "; path=/";
Reading a Cookie with JavaScript
function getCookie(name) {
let cookies = document.cookie.split(';');
for(let cookie of cookies) {
let [cookieName, cookieValue] = cookie.split('=');
if(cookieName.trim() === name) {
return cookieValue;
}
}
return null;
}
console.log(getCookie("username")); // john
PHP Cookies
PHP cookies are set on the server-side using the setcookie() function and sent to the browser via HTTP headers. They must be set before any HTML output.
Setting a Cookie with PHP
<?php
// Set cookie that expires in 1 hour
setcookie("user_preference", "dark_mode", time() + 3600, "/");
?>
Reading a Cookie with PHP
<?php
if (isset($_COOKIE["user_preference"])) {
echo "User preference: " . $_COOKIE["user_preference"];
} else {
echo "No preference set";
}
?>
Key Differences
| Aspect | JavaScript Cookies | PHP Cookies |
|---|---|---|
| Execution | Client-side (browser) | Server-side |
| Setting Method | document.cookie property | setcookie() function |
| Reading Method | Parse document.cookie string | $_COOKIE superglobal |
| Timing | Available immediately | Available on next page request |
| Security | Visible to client scripts | Can be made HTTP-only |
HTTP Headers Example
When PHP sets a cookie, it sends an HTTP header like this ?
HTTP/1.1 200 OK Date: Fri, 04 Feb 2024 21:03:38 GMT Server: Apache/2.4.41 Set-Cookie: user_preference=dark_mode; expires=Fri, 04-Feb-24 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html
Conclusion
JavaScript cookies offer immediate client-side access and manipulation, while PHP cookies provide server-side control with better security options. Choose JavaScript for dynamic user interactions and PHP for secure, server-processed data storage.
