setcookie() must run before output. For HTTPS sites, Secure, HttpOnly and SameSite options are useful defaults for cookies that do not need JavaScript access.
<?php
setcookie('theme', 'dark', [
'expires' => time() + 86400 * 30,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
?>Current example first; the detailed tutorial examples below are retained for additional learning and comparison.
setcookie('Name','value','Expire duration','path','domain', 'secure','httponly')
| Name | Description |
| Name | Required, Name of the cookies to identify |
| Value | Optional , Value to be stored against the Name |
| Expire | Optional , Duration to expire , set relative to current time() in seconds. |
| path | Optional , Should be available throughout domain or particular directory or subdomain |
| domain | Optional , Subdomain to which the cookie is available |
| secure | Optional , if set to true then cookie will be set only when secure connection is available |
| httponly | Optional , if set to true then cookie will be set accessible only through HTTP protocol |
$value="Plus2net Tutorials";
setcookie ("Plus2netCookie", $value,time()+3600);
/* expire in 1 hour */
The above line will set the cookie with the variable value set to a string. This will expire after one hour as the time of expire is set to one hour ( +3600 seconds ) after the current time.
setcookie ("Plus2netCookie", $name,time()+60*60*24*30);
// Expire in 30 days
Two things we have to know here.echo "Welcome " .$HTTP_COOKIE_VARS["Plus2netCookie"];
In PHP 5 and above it is
echo "Welcome " .$_COOKIE["Plus2netCookie"];
setcookie ("Plus2netCookie", "", time() - 3600);
This will delete the cookie.
Tools >> Internet Options >> Privacy then advanced button.
Unlike sessions cookies are managed by users through its web browser so we have to carefully select which data to be used through cookies.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| gsdfg | 20-07-2012 |
| hi very useful this code | |
| Opeyemi Orisatoberu | 04-01-2013 |
| This post is very useful... Tnx... | |
| Freelance Php Developer | 15-08-2017 |
| Nice tutorial. This is fully informative tutorial for set cookies and delete in PHP. It saved lot of time. It just made my work easier. Thanks. | |