Cookies in PHP)

Source: Internet
Author: User
Tags set cookie setcookie
PHP cookies Guide
 Summary

Cookie is a method in which the server or script can maintain information on the customer's workstation under the HTTP protocol. Cookie is a small file stored on the user's browser by the Web server, it can contain information about the user (such as the ID number, password, the user's way of shopping on the web site, or the number of times the user visits the site ). The web site can access cookie information whenever the User links to the server.

  How to Set cookies?

In PHP, you can use the setcookie function to set a cookie. Cookie is part of the HTTP header. Therefore, the cookie setting function must be performed before any content is sent to the browser. This restriction is the same as that of the header () function. Any cookie sent from the client will be automatically converted into a PHP variable. PHP retrieves and analyzes the information header, extracts the cookie name, and changes it to a variable. Therefore, if you set a cookie such as setcookie ("mycookie", "cookies"), PHP will automatically generate a variable named $ mycookie with the value of "cookies.

Let's take a look at the setcookie function Syntax:

Init setcookie (string cookiename, string cookievalue, int cookieexpiretime, path, domain, int secure );

Parameter description:

Path: indicates the Directory on the Web server, which is the directory of the called page by default.

Domain: the domain name that can be used by Cookie. The default value is the domain name of the called page. This domain name must contain two ".", so if you specify your top-level domain name, you must use ".mydomain.com"

Secure: if it is set to "1", it indicates that the cookie can only be remembered by the user's browser as a secure server.

Examples of cookies

Suppose we have a website to be registered, which automatically identifies the user and performs related operations: if it is a registered user, it sends it to him; if you are not a registered user, a link to the registration page is displayed.

According to the above requirements, we first create a database to save the information of registered users: First name, last name, and email address ), counter (visit counter ).

Follow these steps to create a table:

Mysql> create database users;
Query OK, 1 row affected (0.06 Sec)
Mysql> use users;
Database changed
Mysql> Create Table Info (firstname varchar (20), lastname varchar (40), email varchar (40), Count varchar (3 ));
Query OK, 0 rows affected (0.05 Sec)

 

Create a PHP page to check the cookies against the database.

Since PHP can convert identifiable cookies into corresponding variables, we can check a variable named "mycookies:

<? If (isset ($ mycookies) {// If the cookie already exists
......
} Else {// If the cookie does not exist
......
}
?>

When a cookie exists, perform the following steps:

First, obtain the cookie value, use the explode function to analyze different variables, increase the counter, and set a new COOKIE:

$ Info = explode ("&", $ mycookies );
......
$ Count ++;
$ Cookiestring = $ firstname. '&'. $ lastname. '&'. $ email. '&'. $ count;
Setcookie ("mycookies", $ cookiestring, time () + 3600); // set cookie

Then, the user information is output using HTML statements.

Finally, update the database with the new counter value.

If this cookie does not exist, we will display a link to the registration page (register. php.

The following register. php is the user registration page:

/* Register. php */
<Form method = "Post" Action = "regok. php">
First name: <input type = "text" name = "firstname">
Last name: <input type = "text" name = "lastname">
<Input type = "Submit" value = "register">
</Form>

The information you entered on the register. php registration page is submitted to regok. php:

/* Regok. php */
If ($ firstname and $ lastname and $ email ){
...... // Query whether a user exists in the Database
}
} Else {
...... // Handle errors
}

 

The procedure is as follows:

First, check whether all information is filled in as required. If not, return and re-enter

If all the information is filled in, we first retrieve the user logon details from the database.

Mysql_connect () or die ("An error occurred while connecting to the database! ");
$ Query = "select * from info where firstname = '$ firstname' and lastname =' $ lastname' and email = '$ email '";
$ Result = mysql_db_query ("users", $ query );
$ Info = mysql_fetch_array ($ result );
$ COUNT = $ info ["count"];

Check whether the database has such a user. If yes, it specifies the old information and uses the current information to create a new Cookie. If the same user does not log on to the database, create a new database to log on, and create a new cookie.

Now, the isset () function is used to check whether a counter exists. If yes, the counter is added and a new cookie is created:

$ Count ++; // Add a counter
$ Cookiestring = $ firstname. '&'. $ lastname. '&'. $ email. '&'. $ count;
Setcookie ("mycookies", $ cookiestring, time () + 3600 );

If there is no user counter, add a record in MySQL and set a cookie

Note: Before calling the setcookie function, there should be no data output to the browser; otherwise, an error will occur.

How to Implement Cross-Domain Cookie?

According to the cookie specification, a cookie can only be used for one domain name. Therefore, if a cookie is set for a domain name in the browser, the cookie will be invalid for other domain names.

Next we will talk about a Cross-Domain Cookie implementation solution:

Step 1: Create a preset script

Add the following code to the preset script (or appear in the function before all scripts ).

<? PHP
/* If the get variable has been set and is different from the cookie variable
* Use the get variable (update cookie)
*/
Global $ http_cookie_vars, $ http_get_vars;
If (isset ($ sessionid) & isset ($ http_get_vars ['sessionid']) & ($ http_cookie_vars ['sessionid']! = $ Http_get_vars ['sessionid']) {
Setcookie ('sessionid', $ http_get_vars ['sessionid'], 0 ,'/','');
$ Http_cookie_vars ['sessionid'] = $ http_get_vars ['sessionid'];
$ Sessionid = $ http_get_vars ['sessionid'];
}
?>

After the code is run, a global variable 'sessionid' can be used in the script. It will save the sessionid value in your cookie, or the sessionid value sent through the GET request.

Step 2: Use variables for all cross-domain reference

Create a global configuration file to store the basic reference form of domain names that can be switched. For example, if we have domain1.com and domain2.com, the settings are as follows:

<? PHP
$ Domains ['domain1'] = "http://www.domain1.com/-?sessionid -";
$ Domains ['domain2'] = "http://www.domain2.com/-?sessionid -";
?>

Let's write the following code:

<? PHP
Echo "Click <a href =" ", $ domains ['domain2'],"/contact /? Email = yes "> here </a> to contact us .";
?>

The above code will generate the following output:

Click <a href = "http://www.domain2.com/-66543afe6543asdf6asd-/contact? Email = yes "> here </a> to contact us.

Here, sessionid has been inserted into the URL.

Step 3: Configure Apache

Now, configure Apache to rewrite this URL.

We need
Http://www.domain2.com/-66543afe6543asdf6asd-/contact/
The result is as follows:
Http://www.domain2.com/contact? Sessionid = 66543afe6543asdf6asd
And this URL:
Http://www.domain2.com/-66543afe6543asdf6asd-/contact? Email = Yes
The result is as follows:
Http://www.domain2.com/contact? Email = Yes & sessionid = 66543afe6543asdf6asd

To meet the preceding requirements, simply configure two virtual servers as domain1 and domain2. The following operations are performed:

<Virtualhost IPaddress>
DocumentRoot/usr/local/www/domain1
Servername www.domain1.com
Rewriteengine on
Rewriterule ^ /-(.*)-(.*?. *) $2 & sessionid = $1 [L, R, QSA]
Rewriterule ^/-(. *)-(. *) $2? Sessionid = $1 [L, R, QSA]
</Virtualhost>

<Virtualhost IPaddress>
DocumentRoot/usr/local/www/domain2
Servername www.domain2.com
Rewriteengine on
Rewriterule ^ /-(.*)-(.*?. *) $2 & sessionid = $1 [L, R, QSA]
Rewriterule ^/-(. *)-(. *) $2? Sessionid = $1 [L, R, QSA]
</Virtualhost>

These rewrite rules meet the requirements for rewriting the above two URLs.

 

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.