Phpcookie method learning notes sharing. In php, cookies are no different from other programs. cookies are used to store information to clients and are often used in applications with low security requirements, for example, when a user logs on and remembers a password, cookies in php are no different from other programs. cookies are used to store information to clients and are often used in applications with low security requirements, for example, if a user logs on and remembers the password, I will introduce the php cookie learning notes to you.
The PHP 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.
1 setcookie (name, value, expire, path, domain, secure)
• Name is required. Specifies the cookie name.
• Value is required. Specifies the cookie value.
• Expire is optional. Specifies the cookie validity period.
• Path is optional. Specifies the server path of the cookie.
• Optional domain. Specifies the domain name of the cookie.
• Secure is optional. Specifies whether to transmit cookies through secure HTTPS connections.
You can use $ HTTP_COOKIE_VARS ["user"] or $ _ COOKIE ["user"] to access the cookie value named "user. When sending a cookie, the cookie value is automatically URL encoded. URL decoding is performed when receiving the message. If you do not need this, you can use setrawcookie () instead.
For example, php sets and obtains cookies.
The code is as follows: |
|
Setcookie ('mycooker', 'value '); // Function prototype: int setcookie (string name, string value, int expire, string path, string domain, int secure) Echo ($ mycookie ); Echo ($ HTTP_COOKIE_VARS ['mycooker']); Echo ($ _ COOKIE ['mycooker']); |
Delete Cookie
(1) Call setcookie () with only the name parameter ();
(2) set the expiration time to time () or time-1;
The code is as follows: |
|
Setcookie ('mycookier'); or setcookie ('mycookier', ''); or setcookie (" mycookie ", false ); // Setcookie ('mycooker', '', time ()-3600 ); Echo ($ HTTP_COOKIE_VARS ['mycooker']); Print_r ($ _ COOKIE ); |
Recommended deletion methods:
The code is as follows: |
|
Setcookie ('mycooker', '', time ()-3600 ); |
PHP provides a very useful function mktime ().
You only need to transmit it to mktime () in sequence, the hours, minutes, seconds, months, dates, and years you want to represent,
Mktime () returns the total number of seconds from January 1, January 1, 1970.
Therefore, if you need to simulate the Y2K problem:
The code is as follows: |
|
$ Y2k = mktime ); Setcookie ('name', 'value', $ y2k ); Setcookie ('name', 'value', time + 3600 ); Setcookie ('name', 'value', $ y2k ,'~ /Myhome ',' .domain.com '); |
How to get COOKIE expiration time
The code is as follows: |
|
$ Expire = time () + 86400; // Set the 24-hour validity period Setcookie ("var_name", "var_value", $ expire); // set a cookie named var_name with a validity period Setcookie ("var_name_expire", $ expire, $ expire); // Set the Expiration Time to cookie so that you can know the expiration time of var_name |
Note:
When sending a cookie, the cookie value is automatically URL encoded. URL decoding is performed when receiving the message.
If you do not need this, you can use setrawcookie () instead.
For example, cookie to save user login information
1. database connection configuration page: connectvars. php
The code is as follows: |
|
// Database location Define ('Db _ host', 'localhost '); // User name Define ('Db _ user', 'root '); // Password Define ('Db _ password', '123 '); // Database name Define ('Db _ name', 'test '); ?> |
2. logon page: logIn. php
The code is as follows: |
|
// Insert information related to the database connection Require_once 'connectvars. php '; $ Error_msg = ""; // Determine whether the user has set a cookie. if $ _ COOKIE ['User _ id'] is not set, run the following code: If (! Isset ($ _ COOKIE ['User _ id']) { If (isset ($ _ POST ['submit ']) {// determines whether the user has submitted the logon form. if yes, run the following code: $ Dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME ); $ User_username = mysqli_real_escape_string ($ dbc, trim ($ _ POST ['username']); $ User_password = mysqli_real_escape_string ($ dbc, trim ($ _ POST ['password']); If (! Empty ($ user_username )&&! Empty ($ user_password )){ // The SHA () function in MySql is used to encrypt strings in one way. $ Query = "SELECT user_id, username FROM mismatch_user WHERE username = '$ user_username' AND". "password = SHA ('$ user_password ')"; // Query by user name and password $ Data = mysqli_query ($ dbc, $ query ); // If one record is found, set the COOKIE and redirect the page. If (mysqli_num_rows ($ data) = 1 ){ $ Row = mysqli_fetch_array ($ data ); Setcookie ('User _ id', $ row ['User _ id']); Setcookie ('username', $ row ['username']); $ Home_url = 'loged. php '; Header ('Location: '. $ home_url ); } Else {// if the record found is incorrect, the error message is set. $ Error_msg = 'Sorry, you must enter a valid username and password to log in .'; } } Else { $ Error_msg = 'Sorry, you must enter a valid username and password to log in .'; } } } Else {// if the user has logged on, go directly to the logged on page $ Home_url = 'loged. php '; Header ('Location: '. $ home_url ); } ?>
Mismatch-Log In Msimatch-Log In If (empty ($ _ COOKIE ['User _ id']) { Echo' '. $ Error_msg .' '; ?> } ?>
|
3. logon page: loged. php
The code is as follows: |
|
// The logon user name is displayed on the logon page. If (isset ($ _ COOKIE ['username']) { Echo 'you are Logged as '. $ _ COOKIE ['username'].' '; // Click "Log Out" and go to the logOut. php page to Log Out the cookie. Echo 'log Out ('. $ _ COOKIE ['username'].') '; } /** On the logon page, you can use your cookies, such as $ _ cookie ['username'], * $ _ COOKIE ['User _ id'] queries the database, so you can do a lot of things */ ?> |
4. log out cookie page: logOut. php (redirection to lonIn. php after logging out)
The code is as follows: |
|
/** Cancel cookies page */ If (isset ($ _ COOKIE ['User _ id']) { // Set the expiration time of each cookie to a certain time in the past so that they can be deleted by the system, in seconds Setcookie ('User _ id', '', time ()-3600 ); Setcookie ('username', '', time ()-3600 ); } // The location header redirects the browser to another page $ Home_url = 'login. php '; Header ('Location: '. $ home_url ); ?> |
The last three points should be noted.
1: considerations when setting cookies
Setting cookies on the same page is actually performed in the order from the back to the back. if you want to delete a cookie and then write a cookie, you must first write the statement and then write the delete statement. otherwise, an error occurs.
2: example of setcookie
Simple: setcookie ("mycookie", "value_of_mycookie ");
Setcookie ("withExpire", "Expire_in_1_hour", time () + 3600 );
Everything: setcookie ("FullCookie", "Full_cookie_value", time + 3600, "/forum", "www. bKjia. c0m", 1 );
3: Cookies
Cookie is path-oriented. when the default path attribute is used, the WEB server page will automatically pass the current path to the browser. specifying a path will force the server to use the set path.
The cookie set in one directory page is invisible on the page of another directory.
...