Guide to Using cookies in PHP

Source: Internet
Author: User
Summary of cookies in PHP
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.