Loading gists…
A Text snippet, saved for reference.
| 1 | ✅ Concept of Cookies in PHP |
| 2 | Cookies in PHP are small files stored on the client’s browser. They are used to store data (like usernames, preferences, etc.) and send it back to the server with each request. Cookies help maintain stateful information across different pages of a website. |
| 3 | |
| 4 | ⚙️ How Cookies Work in PHP |
| 5 | PHP provides the setcookie() function to create cookies. |
| 6 | |
| 7 | You must call setcookie() before any output is sent to the browser. |
| 8 | |
| 9 | You can retrieve cookies using the $_COOKIE superglobal. |
| 10 | |
| 11 | 📝 Syntax of setcookie() |
| 12 | |
| 13 | setcookie(name, value, expire, path, domain, secure, httponly); |
| 14 | ✅ PHP Script to Set and Retrieve a Cookie |
| 15 | 🔹 1. Set Cookie (set_cookie.php) |
| 16 | |
| 17 | <?php |
| 18 | // Set a cookie named 'user' with value 'John Doe' that expires in 1 hour |
| 19 | setcookie("user", "John Doe", time() + 3600); // 3600 seconds = 1 hour |
| 20 | ?> |
| 21 | |
| 22 | <!DOCTYPE html> |
| 23 | <html> |
| 24 | <head> |
| 25 | <title>Set Cookie</title> |
| 26 | </head> |
| 27 | <body> |
| 28 | <h2>Cookie has been set successfully.</h2> |
| 29 | <a href="get_cookie.php">Click here to view the cookie value</a> |
| 30 | </body> |
| 31 | </html> |
| 32 | 🔹 2. Get Cookie (get_cookie.php) |
| 33 | |
| 34 | <?php |
| 35 | // Check if the 'user' cookie is set |
| 36 | if (isset($_COOKIE["user"])) { |
| 37 | $user = $_COOKIE["user"]; |
| 38 | } else { |
| 39 | $user = "Cookie named 'user' is not set."; |
| 40 | } |
| 41 | ?> |
| 42 | |
| 43 | <!DOCTYPE html> |
| 44 | <html> |
| 45 | <head> |
| 46 | <title>Get Cookie</title> |
| 47 | </head> |
| 48 | <body> |
| 49 | <h2>Cookie Value:</h2> |
| 50 | <p><?php echo $user; ?></p> |
| 51 | </body> |
| 52 | </html> |