A cookie is a small text file which contains information created at server side and store at client browser for tracking or identifying return users.
The PHP setcookie()
function is used to set a cookie.
cookies must be sent before any output(include <html> and <head> tags, any whitespace) from your script.
Syntax
setcookie ($name [, $value[, $expires[, $path [, $domain [, $secure [, $httponly ]]]]]] )
Parameter | Description | Default |
---|---|---|
name | The name of the cookie. | |
value | The value of the cookie. this value is stored on the user's computer,so do not store sensitive information. | "" |
expires | The Unix timestamp time the cookie expires. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes). | 0 |
path | the path on the server in which the cookie will be available on. If set to /bar/, the cookie will be available within /bar/ directory and sub-directories of domain. | "",current directory that the cookie is set in |
domain | the domain that the cookie is available to (such as lautturi.com ). |
"" |
secure | Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. | FALSE |
httponly | When TRUE the cookie will be made accessible only through the HTTP protocol but not scripting languages, such as JavaScript | FALSE |
Example
<?php $value = 'Lautturi'; // create a cookie named username and assign the value. setcookie("username", $value); // expire in 1 hour setcookie("username", $value, time()+3600); // cookie is available to the whole domain(lautturi.com) and within "/backend/" directory,It's transmitted over HTTPS. setcookie("username", $value, time()+3600, "/backend/", "lautturi.com", 1); ?>
Press F12
to open developer tool and view the cookie in your browser:
The PHP superglobal variable $_COOKIE[]
associative array is used to retrieve a cookie value.
The name of your stored cookie is the key and will let you retrieve your stored cookie value!
<?php // Accessing a cookie value if(isset($_COOKIE['username'])) echo $_COOKIE["username"]; ?>
We can use setcookie()
without specifying the value to delete a cookie.
<?php // PHP Delete Cookie setcookie("username"); ?>
We also can use setcookie()
function to set the time the cookie expires and assure that the expiration date is in the past, to trigger the removal mechanism in your browser.
<?php // set the expiration date to one hour ago setcookie("username", "", time() - 3600); ?>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>PHP Remember me using cookie example</title> </head> <body> <form action="login.php" method="POST"> Email: <input name="username" type="text" placeholder="admin"> <br> Password: <input name="password" type="password" placeholder="123"> <br> Remember me: <input type="radio" name="rememberme" value="1" checked> <br> <input type="submit" value="Login"> </form> </body> </html>
login.php
<?php $username = isset($_POST['username'])?trim($_POST['username']):""; $pass = isset($_POST['password'])?trim($_POST['password']):""; $rememberme = isset($_POST['rememberme'])?intval($_POST['rememberme']):0; // verify the user if($username === "admin" && $pass === "123"){ if($rememberme){ // the cookie should be completely random and could not be guessed. // get salt from database, here we use a constant for demonstration // $salt = "lauuser"; // be careful, encrypt token using md5() is not safe now // $userToken = md5("lautturi".$username.$salt); $userToken = "80e4f291f59558362a17000b8118ab56"; $expireTime = time()+24*3600; /* expire in 1 day */ //store the username,token,expireTime into cache or db // saveToDB(array($username,$token,$expireTime)); setcookie("username", $username, $expireTime); setcookie("userToken", $userToken, $expireTime); echo "<p>Set cookie successfully!</p>"; } // Redirect to welcome page echo "<p>Login successfully</p>"; echo "<p>The page will be redirected to welcome page after 4 seconds.</p>" echo <<<EOT <!DOCTYPE html> <html> <head> <meta http-equiv="Refresh" content="5; url=//localhost:82/welcome.php" /> </head> <body> <p>Please follow <a href="//localhost:82/welcome.php">this link</a>.</p> </body> </html> EOT; // die();//The script will keep executing unless you die() } else{ echo '<p><font color="#f00">Invalid username or password</font></p>'; }
welcome.php
<?php if(isset($_COOKIE["userToken"]) && isset($_COOKIE["username"])){ $cookie_userToken = $_COOKIE["userToken"]; $cookie_username = $_COOKIE["username"]; // ensure the usertoken is not modified. // $tmpToken = md5("lautturi".$username.$salt); // if($cookie_userToken!==$tmpToken){ // Invalid token; //} // get the username,token,expireTime. // getDataFromDB() => array($username,$token,$expireTime) $username = "admin"; $token = "80e4f291f59558362a17000b8118ab56"; var_dump($cookie_username); var_dump($cookie_userToken); // verify the username and token if($cookie_username == $username && $cookie_userToken == $token){ echo ""; echo "Hi ".$username; } else{ echo "<a href=\"index.php\">Login</a>"; } } else{ echo "<a href=\"index.php\">Login</a>"; }