08 Jul PHP Cookies
A cookie is a text file in PHP used to identify a user. It is a file the server embeds on the client’s computer. You can easily create, retrieve cookie values, and also delete them.
Cookies Syntax
The setcookie() function is used to create cookies in PHP. Here’s the syntax,
1 2 3 |
setcookie(name, value, expire, path, domain, secure); |
Here,
- name = Name of the cookie. Environment variable HTTP_COOKIE_VARS stores cookies.
- value =The content of the cookie.
- expire = Sets the expiry date of the cookie, after which it will become inaccessible.
- path = Path is the directories for which the cookie will be valid. For allowing the validity of
cookies for all directories, set a single forward slash character. - domain = domain name
- secure = Set to 1 for sending cookies by secure transmission i.e. HTTPS, Set to 0 for sending cookies by HTTP
Set and access Cookies
Here, first we will set cookies for Student Marks. We have also set the cookie value and expiry date of the cookie.
To check if a cookie is set or not, we’re using the isset() function. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php $cookie_name = "marks"; $cookie_marks= "95"; setcookie($cookie_name, $cookie_marks, time() + (3600 * 5), "/"); ?> <html> <body> <?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie: '" . $cookie_name . "' isn’t set. Sorry!"; } else { echo "Cookie Name: '" . $cookie_name . "' set!<br>"; echo "Cookie Value: " . $_COOKIE[$cookie_name]; } ?> </body> </html> |
Here’s the output,
Delete Cookies
Using an expiration date in the past deletes a cookie. Let’s see an example and check how we can use it easily:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php setcookie( "marks", "", time() - 3600); ?> <html> <body> <?php echo "Cookie deleted successfully!" ?> </body> </html> |
No Comments