A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send a cookie too.
PHP can be used to create cookies and retrieve cookie values.
PHP provides the setcookie()
function to set a cookie.
setcookie(name, value, expire, path, domain, security);
Only the
name
parameter is required. All other parameters are optional.
The following code creates a cookie named “admin” with the cookie value “Alex Williams”. The cookie will expire after 30 seconds. The “/” refers to the directory and means that the cookie is available in entire website. Otherwise, the directory can be specified accordingly.
This creates a global variable $_COOKIE
. Values can be retrieved and modifications can be made using this variable. We can also use the isset()
function to verify if the cookie is set:
<!DOCTYPE html><?php$cookie_name = "admin";// modified the cookie_value$cookie_value = "Alex Williams";// set cookie, the cookie will expire in 30 secondssetcookie($cookie_name, $cookie_value, time() + 30, "/");?><html><body><?phpif(!isset($_COOKIE[$cookie_name])) {echo "Cookie named '" . $cookie_name . "' is not set!";} else {echo "Cookie '" . $cookie_name . "' is set!<br>";echo "Value is: " . $_COOKIE[$cookie_name];}?></body></html>
Cookie 'user' is set!
Value is: Alex Porter
To modify a value in a created cookie, use the setcookie()
function again. Look at the code and output below to see this.
A user may been be shown the previous cookie value. In that case, just reload to see the updates.
<!DOCTYPE html><?php$cookie_name = "admin";$cookie_value = "Ross Geller";setcookie($cookie_name, $cookie_value, time() + 30, "/");?><html><body><?phpif(!isset($_COOKIE[$cookie_name])) {echo "Cookie named '" . $cookie_name . "' is not set!";} else {echo "Cookie '" . $cookie_name . "' is set!<br>";echo "Value is: " . $_COOKIE[$cookie_name];}?></body></html>
Cookie 'user' is set!
Value is: Alex Porter
Free Resources