Assign values to cookies
Setcookie (name, value, expire, path, domain)
For example:
The code is as follows: |
Copy code |
<? Php Setcookie ("user", "Alex Porter", time () + 3600 ); ?> |
How can we get the user value?
The code is as follows: |
Copy code |
<? Php Echo $ _ COOKIE ["user"]; Print_r ($ _ COOKIE ); ?> |
If we do not set the user cookie, an error will occur during execution, so that we can use the isset function for judgment.
The code is as follows: |
Copy code |
<? Php If (isset ($ _ COOKIE ["user"]) Echo "Welcome". $ _ COOKIE ["user"]. "! <Br> "; Else Echo "Welcomeguest! <Br> "; ?> |
Chinese characters are always garbled
For example, "% u5C0F % u4F1F" is obtained by "Xiaowei"
This is not garbled, but unicode encoding. In php, there is a built-in function called unicode_encode that can convert a unicode string into the desired encoding method. The Function prototype is: string unicode_encode (unicode input, string encoding)
Here is an example for reference:
The code is as follows: |
Copy code |
<? Php Header ('content-Type: text/plain; charset = ISO-8859-2 '); $ Encoded = unicode_encode ('\ u0150 \ u0179', 'ISO-8859-2 '); Echo 'unicode semantics: ', ini_get ('unicode _ semantics'), PHP_EOL, 'The string itself :'; Printf ($ encoded. PHP_EOL, '% s '); Echo 'The length of The string: ', strlen ($ encoded ); ?> |
Use js + php for page browsing statistics
The code is as follows: |
Copy code |
// Page views $ Visited = (int) $ _ COOKIE ['pagevisits '] + 1; Setcookie ('pagevisits ', // cookie name $ Visited, // cookie value Time () + 7*24*60*60 // expiration time ); |
When the page is running, the server will write a cookie value to save the number of times you visit the page. The setcookie method of php is applied here.
Output this value:
Now let's take a look at how to use js to get and set cookies.
The code is as follows: |
Copy code |
Var cookie = $. cookie ('democookie '); If (cookie) $ ('. jq-text'). text (cookie). show (); $ ('. Fields a'). click (function (e ){ Var text = $ ('# inputbox'). val (); // Set the cookie value $. Cookie ('democookie ', text, {expires: 7 }); $ ('. Jq-text'). text (text). slideDown ('low '); E. preventDefault (); }); $ ('# Form1 & prime;). submit (function (e) {e. preventDefault ();}) Var cookie = $. cookie ('democookie '); Obtain the value of the key name demoCookie (if null is not returned ). $. Cookie ('democookie ', text, {expires: 7 }); |
When you click save, the value of the input box is written into the cookie.