Phpcookie method learning notes sharing

Source: Internet
Author: User
Tags http cookie
In php, cookies are no different from other programs. cookies are used to store information to clients. they are often used in applications with low security requirements, such as logging on to users and remembering passwords.

In php, cookies are no different from other programs. cookies are used to store information to the client. they are often used in applications with low security requirements, such as logging on to users and remembering passwords, next I will introduce the php cookie study notes.

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 retrieves cookies. the code is as follows:

  1. Setcookie ('mycooker', 'value ');
  2. // Function prototype: int setcookie (string name, string value, int expire, string path, string domain, int secure)
  3. Echo ($ mycookie );
  4. Echo ($ HTTP_COOKIE_VARS ['mycooker']);
  5. 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:

  1.  
  2. Setcookie ('mycookier'); or setcookie ('mycookier', ''); or setcookie (" mycookie ", false );
  3. // Setcookie ('mycooker', '', time ()-3600 );
  4. Echo ($ HTTP_COOKIE_VARS ['mycooker']);
  5. Print_r ($ _ COOKIE );

It is recommended to delete the code as follows:

Setcookie ('mycooker', '', time ()-3600 );

PHP provides a very useful function mktime ().

You only need to transmit the data to mktime () in sequence, the number of hours, minutes, seconds, months, dates, and years that you want to represent, mktime () will return the total number of seconds of the date from January 1, January 1, 1970, therefore, if you need to simulate the Y2K problem, the code is as follows:

  1. $ Y2k = mktime );
  2. Setcookie ('name', 'value', $ y2k );
  3. Setcookie ('name', 'value', time + 3600 );
  4. Setcookie ('name', 'value', $ y2k ,'~ /Myhome ',' .domain.com ');

How to obtain the COOKIE expiration time,The code is as follows:

  1. $ Expire = time () + 86400; // Set the 24-hour validity period
  2. Setcookie ("var_name", "var_value", $ expire); // set a cookie named var_name with a validity period
  3. 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 during Receiving. if you do not need this, you can use setrawcookie () instead.

For example, cookie to save user login information

1. on the database connection configuration page, connectvars. php, the code is as follows:

  1. // Database location
  2. Define ('Db _ host', 'localhost ');
  3. // User name
  4. Define ('Db _ user', 'root ');
  5. // Password
  6. Define ('Db _ password', '123 ');
  7. // Database name
  8. Define ('Db _ name', 'test ');
  9. ?>

2. logon page: logIn. php. the code is as follows:

  1. // Insert information related to the database connection
  2. Require_once 'connectvars. php ';
  3. $ Error_msg = "";
  4. // Determine whether the user has set a cookie. if $ _ COOKIE ['User _ id'] is not set, run the following code:
  5. If (! Isset ($ _ COOKIE ['User _ id']) {
  6. If (isset ($ _ POST ['submit ']) {// determines whether the user has submitted the logon form. if yes, run the following code:
  7. $ Dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
  8. $ User_username = mysqli_real_escape_string ($ dbc, trim ($ _ POST ['username']);
  9. $ User_password = mysqli_real_escape_string ($ dbc, trim ($ _ POST ['password']);
  10. If (! Emptyempty ($ user_username )&&! Emptyempty ($ user_password )){
  11. // The SHA () function in MySql is used to encrypt strings in one way.
  12. $ Query = "SELECT user_id, username FROM mismatch_user WHERE username = '$ user_username' AND". "password = SHA ('$ user_password ')";
  13. // Query by user name and password
  14. $ Data = mysqli_query ($ dbc, $ query );
  15. // If one record is found, set the COOKIE and redirect the page.
  16. If (mysqli_num_rows ($ data) = 1 ){
  17. $ Row = mysqli_fetch_array ($ data );
  18. Setcookie ('User _ id', $ row ['User _ id']);
  19. Setcookie ('username', $ row ['username']);
  20. $ Home_url = 'loged. php ';
  21. Header ('Location: '. $ home_url );
  22. } Else {// if the record found is incorrect, the error message is set.
  23. $ Error_msg = 'Sorry, you must enter a valid username and password to log in .';
  24. }
  25. } Else {
  26. $ Error_msg = 'Sorry, you must enter a valid username and password to log in .';
  27. }
  28. }
  29. } Else {// if the user has logged on, go directly to the logged on page
  30. $ Home_url = 'loged. php ';
  31. Header ('Location: '. $ home_url );
  32. }
  33. ?>
  34.  
  35.  
  36. Mismatch-Log In 
  37.  
  38.  
  39.  
  40. Msimatch-Log In
  41.  
  42. If (emptyempty ($ _ COOKIE ['User _ id']) {
  43. Echo' '. $ Error_msg .'

    ';
  44. ?>
  45.  
  46. }
  47. ?>
  48.  
  49.  

3. log on to the loged. php page. the code is as follows:

  1. // The logon user name is displayed on the logon page.
  2. If (isset ($ _ COOKIE ['username']) {
  3. Echo 'you are Logged as '. $ _ COOKIE ['username'].'
    ';
  4. // Click "Log Out" and go to the logOut. php page to Log Out the cookie.
  5. Echo 'log Out ('. $ _ COOKIE ['username'].') ';
  6. }
  7. /** On the logon page, you can use your cookies, such as $ _ cookie ['username'],
  8. * $ _ COOKIE ['User _ id'] queries the database, so you can do a lot of things */
  9. ?>

4. log out of the cookie page and logOut. php (redirection to lonIn. php after logging out). The code is as follows:

  1. /** Cancel cookies page */
  2. If (isset ($ _ COOKIE ['User _ id']) {
  3. // 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
  4. Setcookie ('User _ id', '', time ()-3600 );
  5. Setcookie ('username', '', time ()-3600 );
  6. }
  7. // The location header redirects the browser to another page
  8. $ Home_url = 'login. php ';
  9. Header ('Location: '. $ home_url );
  10. ?>

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); setcookie ("FullCookie", "Full_cookie_value", time + 3600, "/forum", "www.phpfensi.com", 1 );

3: Cookies

Cookie is path-oriented. by default, the WEB server page will automatically pass the current path to the browser. the specified 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.