PHP Cookies
What is a Cookie?
A cookie is a little piece of data that is used to identify a person (from a specific device).
Cookie is a small file that the server stores on the computer of the user.
The cookie will be sent each time the same computer requests a page using a browser.
Cookie values can be created and retrieved with PHP.
PHP Create/Retrieve a Cookie
The setcookie()
function is used to creates a cookie.
The $_COOKIE
is a global variable and used to retrieve an existing cookie.
The isset()
function is used to check whether or not the cookie has been set or created.
Syntax :-
setcookie(name, value, expire, path, domain, secure, httponly);
The name argument is the only one that required. The rest of the parameters are purely optional.
Example :- The example below produces a "user" cookie of the "abc" value. After 30 days (86400 * 30), the cookie expires. The "/" indicates that the cookie is present on the whole site (otherwise, select the directory you prefer) :
";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
Output:-
Note: You might have to reload the page to see the value of the cookie.
Output:- After refresh the page
Value is: abc
Note :- The setcookie()
function must occur before the
html
tag, or before sending any text to the browser screen.
When delivering the cookie, the value is automatically URLencoded, and when receiving the cookie, it is automatically decoded (to avoid URLencoding, use setrawcookie()
instead).
Modify a Cookie Value
The setcookie()
function is also used to change or modify a exiting cookie value.
Example :-
Output :-
Note: You might have to reload the page to see the new value of the cookie.
Related Links
Delete a Cookie
The setcookie()
function is also used to remove an existing cookie by setting an expiration date
in the past.
Example :- We are deleting the "user" cookie by setting time one hour ago.
Output :-
Check if Cookies are Enabled
The following instance produces a simple script that verifies the activation of cookies. Try creating a test cookie using the setcookie()
feature and then count the array variable $_COOKIE
:
0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
Output :-
Related Links