Php cookie 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 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 obtains cookies.

The Code is as follows: Copy code

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: Copy code

<? Php setcookie ('name');?>

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: Copy code

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: Copy code

$ 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: Copy code

$ 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: Copy code

<? Php
// 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: Copy code

<? Php
// 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 );
}
?>
<Html>
<Head>
<Title> Mismatch-Log In </title>
<Link rel = "stylesheet" type = "text/css" href = "style.css"/>
</Head>
<Body>
<H3> Msimatch-Log In <! -- Judge by $ _ COOKIE ['user _ id']. If the user is not logged on, the logon form is displayed, asking the user to enter the user name and password -->
<? Php
If (empty ($ _ COOKIE ['user _ id']) {
Echo '<p class = "error">'. $ error_msg. '</p> ';
?>
<! -- $ _ SERVER ['php _ SELF '] indicates that when a user submits a form, the user calls his/her own PHP file. -->
<Form method = "post" action = "<? Php echo $ _ SERVER ['php _ SELF '];?> ">
<Fieldset style = "width: 250px;">
<Legend> Log In </legend>

<Label for = "username"> Username: </label>
<! -- If the user name has been lost, the user name is displayed. -->
<Input type = "text" id = "username" name = "username"
Value = "<? Php if (! Empty ($ user_username) echo $ user_username;?> "/>
<Br/>
<Label for = "password"> Password: </label>
<Input type = "password" id = "password" name = "password"/>
</Fieldset>
<Br/>
<Input type = "submit" value = "Log In" name = "submit"/>
</Form>
<? Php
}
?>
</Body>
</Html>

3. logon page: loged. php

 

The Code is as follows: Copy code
<? Php
// The logon user name is displayed on the logon page.
If (isset ($ _ COOKIE ['username']) {
Echo 'you are Logged as '. $ _ COOKIE ['username'].' <br/> ';
// Click "Log Out" and go to the logOut. php page to Log Out the cookie.
Echo '<a href = "logOut. php"> Log Out ('. $ _ COOKIE ['username']. ') </a> ';
}
/** 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: Copy code
<? Php
/** 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.

Related Article

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.