Introduction to Cookies in PHP
A cookie is a small piece of data that is stored on the user’s browser and sent back to the server with each request. Cookies are commonly used for tracking user behavior, storing user preferences, and maintaining session states.
How Cookies Work in PHP?
- The server sets a cookie using the setcookie() function.
- The cookie is stored in the user’s browser.
- The browser sends the cookie back to the server with every request.
- The server reads the cookie and processes the request accordingly.
Cookie Syntax in PHP
setcookie(name, value, expire, path, domain, secure, httponly);
Parameter | Description |
name | The name of the cookie (string). |
value | The value stored in the cookie (string). |
expire | Expiration time (timestamp). If set to 0, it expires when the browser closes. |
path | The directory where the cookie is available (default: /, available site-wide). |
domain | The domain name where the cookie is available. |
secure | If true, the cookie is sent only over HTTPS. |
httponly | If true, the cookie is inaccessible via JavaScript (prevents XSS attacks). |
Setting a Cookie in PHP
To store a cookie, use the setcookie() function before any HTML output.
Example: Storing a Cookie
<?php
$cookie_name = “user”;
$cookie_value = “JohnDoe”;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), “/”); // Cookie expires in 30 days
echo “Cookie named ‘” . $cookie_name . “‘ is set!”;
?>
Retrieving a Cookie in PHP
To read a cookie, use the $_COOKIE superglobal.
Example: Retrieving a Cookie
<?php
if(isset($_COOKIE[“user”])) {
echo “Welcome back, ” . $_COOKIE[“user”] . “!”;
} else {
echo “No cookie found.”;
}
?>
Deleting a Cookie in PHP
To delete a cookie, set its expiration time in the past.
Example: Deleting a Cookie
<?php
setcookie(“user”, “”, time() – 3600, “/”); // Expire the cookie
echo “Cookie deleted.”;
?>
Advantages of Cookies
- Stores user preferences for a better user experience.
- Reduces server workload by storing state information on the client-side.
- Helps in tracking user behavior for analytics and advertising.
Disadvantages of Cookies
- Security Risks: Can be stolen via XSS (Cross-Site Scripting).
- Limited Storage: Can store only 4KB of data per cookie.
- Dependent on Browser Settings: Users can disable cookies, limiting functionality.
Understanding HTTP in PHP
What is HTTP?
HTTP (Hypertext Transfer Protocol) is a stateless protocol used for communication between web clients (browsers) and web servers. It defines how messages are formatted and transmitted.
HTTP Request-Response Cycle
- Client (browser) sends a request to the server.
- Server processes the request and sends a response.
- Client receives the response (HTML, JSON, XML, etc.).
Example: HTTP Request and Response
1. Client Request (From Browser to Server)
GET /index.php HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Cookie: user=JohnDoe
2. Server Response (From Server to Browser)
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: session_id=xyz123; HttpOnly
Handling HTTP Headers in PHP
PHP allows you to read and modify HTTP headers using the header() function.
Setting a Custom HTTP Header
<?php
header(“Content-Type: application/json”); // Send response as JSON
echo json_encode([“message” => “Hello, World!”]);
?>
Redirecting Users Using HTTP Headers
<?php
header(“Location: https://www.example.com”);
exit();
?>
Setting Cache-Control Headers
<?php
header(“Cache-Control: no-cache, must-revalidate”);
?>
HTTP Methods in PHP
PHP can handle different HTTP request methods using the $_SERVER superglobal.
1. Handling GET Requests
<?php
if ($_SERVER[“REQUEST_METHOD”] == “GET”) {
echo “This is a GET request!”;
}
?>
2. Handling POST Requests
<?php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
echo “Received POST request with data: ” . $_POST[“name”];
}
?>
3. Handling JSON Requests (API Example)
<?php
$data = json_decode(file_get_contents(“php://input”), true);
echo “Received data: ” . $data[“name”];
?>
Difference Between Cookies and Sessions
Feature | Cookies | Sessions |
Storage Location | Stored on the client’s browser | Stored on the server |
Security | Less secure (can be modified by users) | More secure (data is not exposed to the user) |
Data Expiry | Can persist beyond browser closure | Ends when the user closes the browser or logs out |
Size Limit | Limited to 4KB | No fixed limit |
Usage | Stores preferences, tracking data | Stores user authentication, temporary data |
Conclusion
- Cookies store small data on the user’s browser for tracking and user preferences.
- HTTP is the communication protocol used by PHP to send and receive data.
- HTTP headers control caching, redirects, security policies, and API responses.