The setcookie () function sends an HTTP cookie to the client.
Cookie is a variable sent from the server to the browser. Cookies are usually small text files embedded into users' computers by servers. This cookie is sent every time a computer requests a page through a browser.
The cookie name is a variable with the same name. For example, if the sent cookie is named "name", a variable named $ user is automatically created, containing the cookie value.
The cookie must be assigned a value before any other output is sent.
If the call succeeds, the function returns true; otherwise, the function returns false.
Syntax
Setcookie (name, value, expire, path, domain, secure)
Example
The code is as follows: |
Copy code |
Makecookie ('20140901', 'www .111cn.net '); // Clear cookie Clearcookies (); // A second-level domain name cookie function is supported below. Function setcookielive ($ name, $ value = '', $ expire = 0, $ path ='', $ domain = '', $ secure = false, $ httponly = false ){ // Set a cookie as usual, but also add it to $ _ cookie so the current page load has access $ _ Cookie [$ name] = $ value; Return setcookie ($ name, $ value, $ expire, $ path, $ domain, $ secure, $ httponly ); } // Call method Setcookielive ('webb', '111cn', time () + 86000, '/', '111cn. Net '); // Entry-level cookie setting method Setcookie ("cookie [three]", "cookiethree "); Setcookie ("cookie [two]", "cookietwo "); Setcookie ("cookie [one]", "cookieone "); // After the page reloads, print them out If (isset ($ _ cookie ['cookies']) { Foreach ($ _ cookie ['cooker'] as $ name => $ value ){ Echo "$ name: $ value <br/> n "; } } |
How to obtain the cookie in js
The code is as follows: |
Copy code |
<Html> <Head> <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"> <Title> Insert title here </title> </Head> <Body> <Script type = "text/javascript"> // Get cookie Function getCookie (name ){ Var nameEQ = name + "= "; Var ca = document. cookie. split (';'); For (var I = 0; I <ca. length; I ++ ){ Var c = ca [I]; While (c. charAt (0) = ''){ C = c. substring (1, c. length ); } If (c. indexOf (nameEQ) = 0 ){ Return unescape (c. substring (nameEQ. length, c. length )); } } Return false; } // Clear cookie Function clearCookie (name ){ SetCookie (name, "",-1 ); } // Set cookie Function setCookie (name, value, seconds ){ Seconds = seconds | 0; Var expires = ""; If (seconds! = 0 ){ Var date = new Date (); Date. setTime (date. getTime () + (seconds * 1000 )); Expires = "; expires =" + date. toGMTString (); } Document. cookie = name + "=" + escape (value) + expires + "; path = /"; } Alert (getCookie ('test2 ')); </Script> </Body> </Html> |