CSC329 ยท 2081 ยท 5 marks
Define cookie. Write a PHP program to create and retrieve a cookie.
Define cookie. Write a PHP program to create and retrieve a cookie. [5]
Quick answer
A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. Cookies are used to identify users and store information between page requests. Examples of cookies include Name cookie, Date cookie, etc.
Cookie: Definition and PHP Program
Definition of Cookie
PHP can send and receive cookies.
PHP Program to Create and Retrieve a Cookie
Step 1: Create (Set) a Cookie
<?php
// Setting a cookie
// setcookie(name, value, expiry_time)
$cookie_name = "username";
$cookie_value = "JohnDoe";
// Cookie expires in 1 day (time() + 86400 seconds)
setcookie($cookie_name, $cookie_value, time() + 86400);
echo "Cookie has been set successfully!";
?>
Step 2: Retrieve (Read) a Cookie
<?php
// Retrieving the cookie
if (isset($_COOKIE["username"])) {
echo "Cookie Found! ";
echo "Username is: " . $_COOKIE["username"];
} else {
echo "Cookie is not set.";
}
?>
Complete Program (Create and Retrieve in One File)
<?php
// Step 1: Create/Set the cookie
$cookie_name = "username";
$cookie_value = "JohnDoe";
// setcookie must be called before any HTML output
setcookie($cookie_name, $cookie_value, time() + 86400); // expires in 1 day
?>
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<?php
// Step 2: Retrieve the cookie
if (isset($_COOKIE["username"])) {
echo "<p>Cookie Name : username</p>";
echo "<p>Cookie Value : " . $_COOKIE["username"] . "</p>";
} else {
echo "<p>Cookie is not set yet. Please refresh the page.</p>";
}
?>
</body>
</html>
Output
Cookie Name : username
Cookie Value : JohnDoe
Key Points
| Function / Variable | Purpose |
|---|---|
setcookie() | Creates/sets a cookie on the client's computer |
$_COOKIE[] | Superglobal array used to retrieve cookie values |
isset() | Checks whether the cookie exists before reading |
time() + 86400 | Sets expiry to 1 day (86400 seconds) from now |
Note:
setcookie()must be called before any HTML output, otherwise the cookie will not be set.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.