The setcookie () function is a function in php used to set the cookie value. Next I will summarize the specific usage of the setcookie () function and how to obtain the cookie value after setting.
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. bKjia. c0m '); // 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, '/', 'bkjia. c0m '); // 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> |