search
HomeBackend DevelopmentPHP TutorialDetailed explanation of how to use cookies in PHP

Detailed explanation of how to use cookies in PHP

May 23, 2018 pm 01:46 PM
cookiephpInstructions

This article mainly introduces the use of cookies in PHP: adding/updating/deleting/getting cookies, automatically filling in the user's user name and password, and determining whether to log in for the first time. It has a good reference value. Let's take a look at it with the editor

The use of cookies in PHP---add/update/delete/get cookies and automatically fill in the user's user name and password and determine whether it is the first time to log in

What is a cookie

The server saves user information on the client, such as login name, password, etc.

These data are like cookies. The amount of data is not large. The server can read it from the client when needed and save it in the client's browser cache directory.

① When the browser accesses, cookie.php, the server will also send an http response with Set-Cookie:name=zxf;expire=Wed,21-Sep-2017 20:14 GMT. When the browser obtains the message, it will save the cookie information. To local disk

② If we don’t have time (the third parameter)

The cookie will not be saved to the client. When the browser session ends, the cookie will expire

③ The cookie saves string information

④ The client can save multiple keys=>val

⑤ During the saving process of the cookie, Chinese will be urlencoded

Cookies can have multiple key=>val, and different key values ​​can be assigned different validity times

The code is as follows: xx.php

<?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 "成功";
 ?>

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

Determine whether it is the first time to log in

<?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);

}
?>

When you open the login interface, automatically fill in the user name 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);

}
}

The above is the entire content of this article, I hope It will be helpful to everyone’s study.


##Related recommendations:

Use ajaxfileupload.js to implement ajax upload file php version_jquery

Character processing performance comparison between #Node.js, PHP, and Python_node.js

Convert the URL address in the text into a Click the link JavaScript, PHPCustom function_javascript skills

The above is the detailed content of Detailed explanation of how to use cookies in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.