Home  >  Article  >  How to use cookies in php

How to use cookies in php

无忌哥哥
无忌哥哥Original
2018-06-28 11:11:471841browse

* The biggest difference between cookies and sessions:

* The cookie is saved in the client browser

* The session is saved on the server, and the client ID saved in the cookie is used for query

* All sessions are based on cookies, so we must first learn how to use php to set cookies for the client

* Let the server remember the visitor

/ /1. Set cookie (name, value, expire)

//The cookie name is also a variable, and it must also follow PHP’s naming rules for variable identifiers

setcookie('username', 'peter zhu',time()+60*10);  //10分钟后过期
setcookie('email', 'peter@php.cn');

//2. View cookie: Use the super global variable $_COOKIE

//Why do we need to do it twice? The first time is to set it, and the second time is to check the new value

echo &#39;用户名: &#39;,$_COOKIE[&#39;username&#39;],&#39;<br>&#39;;
echo &#39;邮箱: &#39;,$_COOKIE[&#39;email&#39;],&#39;<br>&#39;;

//3. Update cookie:

//Turn off the previous set cookie statement first, and refresh it twice to see the new value

setcookie(&#39;username&#39;,&#39;朱老师&#39;);

//3. Delete cookie: setcookie()

//Note 1 :Please turn off the previous setting statement

//Note 2: Only the value has been deleted and cannot be accessed anymore, but the cookie variable name still exists

//Method 1: setcookie(name ), only pass cookie name

setcookie(&#39;username&#39;);

//Method 2: setcookie(name), pass null value

setcookie(&#39;username&#39;,&#39;&#39;);

//Method 3: setcookie(name,'',time()-x ): Pass an expired time at will

setcookie(&#39;username&#39;,&#39;&#39;,time()-3600);

//5. Physically delete the cookie: unset($_COOKIE[name]), completely destroy the cookie, and it is finally safe

unset($_COOKIE[&#39;username&#39;]);
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