(1) Browser viewing cookies:
Name, Value, Domain domain name, Path, Expires/Max-Age expiration time,
Size, HTTP, Secure, Samesite Same Site
When sending a request, the name and value of the cookie will be sent to the server, and the server will not process the expired data
(2) PHP sets cookies through setcookie()
bool setcookie( string $name; //Specify the cookie name [,string $value] //Specify cookie value [,int $expiration time = 0] //Specify the validity period of the cookie [,path $path] //Specify the server path of the cookie [,string $domain name] //Specify the domain name of the cookie [,bool $secure=false] // secure, whether to transmit cookies over a secure HTTPS connection [,bool $http read-only = false] //If true, JS cannot modify the cookie to increase security );
Generally speaking, 3 parameters are enough, key, value, validity period
And generally do not write the username and password into the cookie, because it is very insecure
(3) Here is an example
Username and password are stored as cookies with a time limit of 60 seconds
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> demo measurement </ title> </head> <body> <form action="./cookie.php" method="post"> 姓名:<input type="text" name="username"><hr> 密码:<input type="password" name="pwd"><hr> <input type="submit" value="submit button"> </form> </body> </html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <?php //connect to the user database include 'config.php'; $connect = mysqli_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME); if(!$connect){ die("could not connect:".mysqli_error()); }else{ echo "Connection succeeded<br>"; //Visit again, identified by cookie if (($_COOKIE['username'] != null)&&($_COOKIE['password'] != null)) { echo "COOKIE exists and can be used <br>"; $username = $_COOKIE['username']; $password = $_COOKIE['password']; }else{ echo "COOKIE expired"; } if(($_POST['username'] != null)&&($_POST['pwd'] != null)){ $username = $_POST['username']; $password = $_POST['pwd']; //retrieve data $sql = "select* from user where name='$username'"; $result = mysqli_query($connect,$sql); $row = mysqli_fetch_array($result); // get the correct password var_dump($row['password']); if ($row['password'] == $password) { //Password verification, set cookie, save the username and password on the client setcookie('username',$username,time()+60);//Set the time limit to 60 seconds, the cookie will expire after 60 seconds setcookie('password',$password,time()+60); //Jump to the welcome interface after login header('Location:welcome.php'."?username=$username"); }else{ echo "Incorrect username or password"; } }else{ echo "Please enter username or password"; } } //close the connection $close = mysqli_close($connect); if(!$close){ die("Failed to close the database"); }else{ echo "Close successfully"; } ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <?php echo "Welcome"; ?>
.