What are the uses of cookies in php

王林
Release: 2023-03-04 16:14:01
Original
1696 people have browsed it

Cookies in php can be used to automatically fill in the user's username and password, and determine whether it is the first time to log in. A cookie is a small file that the server leaves on the user's computer. When the same computer requests a page through the browser, the cookie will be sent by the computer.

What are the uses of cookies in php

Introduction to cookie definition and usage:

A cookie is a small file left by the server on the user's computer.

(Recommended tutorial: php graphic tutorial)

Every time the same computer requests a page through the browser, this computer will send a cookie. With PHP, you can create and retrieve cookie values.

Example:

Add/Update/Delete/Get Cookie

<?php
//添加cookie
setcookie("name","zxf",time()+3600);
//数组
 
/$arr = array(1,2,3); 
 $arr_str = serialize($arr); 
 setcookie("a",$arr_str,time()+3600); 
 
//获取cookie
  
var_dump($_COOKIE);
 
//更新cookie
 
setcookie("name","aaa",time()+3600);
 
//删除cookie
 
setcookie("name","",time()-20);
 
//删除所有
 
foreach ($_COOKIE as $key => $value) {
 setcookie($key,"",time()-1);
 }
echo "成功";
 ?>
Copy after login

If the key=>val of the cookie you delete is not deleted, the cookie is on the client Keep, if you delete all cookies on this website, the browser will delete the cookie file.

(Video tutorial recommendation: php video tutorial)

Judge whether to log in for the first time

<?php
 
//先判断cookie里是否有上次的登录信息
 
if(!empty($_COOKIE[‘lastVisit&#39;])){
 
  echo “你上次登陆的时间是”.$_COOKIE[‘lastViat&#39;];
 
//更新时间
 
setcookie(“lastVisit”,”data(Y-m-d H:i:s)”, time()+3600);
 
}else{
 
//说明用户是第一次登陆
 
echo”第一次登陆”;
 
//更新时间
 
setcookie(“lastViait”,”data(“Y-m-d H:i:s”)”, time()+3600);
 
}
?>
Copy after login

When you open the login interface, automatically fill in the user username and password.

checklogin.php

//获取用户是否选中了保存id
 
if(!empty($_POST[‘cookie&#39;])){
 
  setcookie(“id”,$id,time()-100);
 
}else{
 
  if(!empty($_COOKIE[‘id&#39;])){
 
   setcookie(“id”,$id,time()-10);
 
}
}
Copy after login

The above is the detailed content of What are the uses of cookies in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template