Summary
Cookies are a way in which servers or scripts can maintain information on client workstations under the HTTP protocol. A cookie is a small file saved by a web server on the user's browser. It can contain information about the user (such as an identification number, password, how the user shops on the Web site or how many times the user visits the site). Cookie information can be accessed by the web site whenever a user links to the server.
How to set cookies?
In PHP, you can use the setcookie function to set a cookie. Cookies are part of the HTTP header, so setting the cookie function must be before any content is delivered to the browser. This limitation is the same as the header() function. Any cookies coming from the client will be automatically converted into a PHP variable. PHP obtains information headers and analyzes them, extracts the cookie name and turns it into a variable. Therefore, if you set cookies such as setcookie("mycookie","Cookies")php will automatically generate a variable named $mycookie and the value "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: represents the directory on the web server, and the default is the directory where the page is called is located.
DOMAIN: The domain name that can be used by cookies is the domain name of the called page by default. This domain must contain two ".", so if you specify your top-level domain, you must use "."
SECURE: If set to "1", it means that the cookie can only be remembered by the user's browser as a secure server.
Examples of use of cookies
Suppose we have such a site that needs to be registered, which automatically recognizes the user's identity and performs related operations: if it is a registered user, send information to him; if it is not a registered user, a link to the registration page will be displayed.
According to the above requirements, we first create a database to save the information of registered users: first name, last name, email address, and counter.
First, follow the steps below 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)
Then create a php page to check cookies against the database.
Since PHP can convert recognizable 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, we perform the following steps:
First, get the cookie value, use the exploit function to analyze it into different variables, add the counter, and set a new cookie:
$info = explode("&", $myCookies);
……
$count++;
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("myCookies",$CookieString, time()+3600); //Set cookies
Then use the html statement to output user information.
Finally, update the database with the new counter value.
If this cookie does not exist, we display a link to the registration page().
The following is the user registration page:
/* */
<form method="post" action="">
First Name:<input type="text" name="FirstName">
Last Name:<input type="text" name="LastName">
<input type="submit" value="registration">
</form>
Submit the information filled in by the user on the registration page to:
/* */
if ($FirstName and $LastName and $email) {
…//Query the user in the database if it exists
}
}else{
…//Error handling
}
The above program flow is as follows:
First check whether all the information is filled in as required. If not, return and re-enter.
If all the information is filled in, first, we will retrieve the user login details from the database.
mysql_connect() or die ("An error occurred 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 there is, it specifies the old information and uses the current information to create a new cookie. If the same user does not have a database login, create a new database login and create a new cookie.
Now use isset() function to check whether the user has a counter. If so, the counter will increase and create a new cookie:
$count++;//Increase the 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: No data should be output to the browser before calling the setcookie function, otherwise an error will occur.
How to implement cross-domain name cookies?
From the cookie specification, a cookie can only be used for one domain name. Therefore, if a cookie is set to a domain name in the browser, then this cookie will be invalid for other domain names.
Let’s talk about the implementation plan of cross-domain cookies:
Step 1: Create a preset script
Add the following code to the preset script (or appears in the functions that precede all scripts).
<?php
/*If the GET variable has been set and it is different from the cookie variable
* Use the get variable (update cookies)
*/
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 this code is run, a global variable 'sessionid' will be available for the script. It will save the sessionid value in the user's cookie, or the sessionid value sent via the GET request.
Step 2: Use variables for all cross domain references
Create a global configuration file to store the basic reference form of domain names that can be switched. For example, if we have the sum, then set it as follows:
<?php
$domains['domain1'] = "http:///-$sessionid-";
$domains['domain2'] = "http:///-$sessionid-";
?>
Let's write a code like this:
<?php
echo "Click <a href="", $domains['domain2'], "/contact/?email=yes">here</a> to contact us.";
?>
The above code will produce the following output:
Click <a href="http:///-66543afe6543asdf6asd-/contact/?email=yes">here</a> to contact us.
Here the sessionid has been inserted into the URL.
Step 3: Configure Apache
Now, let's configure Apache to rewrite this URL.
We need to
http:///-66543afe6543asdf6asd-/contact/
It became like this:
http:///contact/?sessionid=66543afe6543asdf6asd
And this kind of url:
http:///-66543afe6543asdf6asd-/contact/?email=yes
It became like this:
http:///contact/?email=yes&sessionid=66543afe6543asdf6asd
In order to achieve the above requirements, two virtual servers are simply configured as domain1 and domain2, as follows:
<VirtualHost ipaddress>
DocumentRoot /usr/local/www/domain1
ServerName
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
RewriteEngine on
RewriteRule ^/-(.*)-(.*?.*)$ $2&sessionid=$1 [L,R,QSA]
RewriteRule ^/-(.*)-(.*)$ $2?sessionid=$1 [L,R,QSA]
</VirtualHost>
These rewrite rules implement the requirements of rewriting the two URLs above.
Cookies are a way in which servers or scripts can maintain information on client workstations under the HTTP protocol. A cookie is a small file saved by a web server on the user's browser. It can contain information about the user (such as an identification number, password, how the user shops on the Web site or how many times the user visits the site). Cookie information can be accessed by the web site whenever a user links to the server.
How to set cookies?
In PHP, you can use the setcookie function to set a cookie. Cookies are part of the HTTP header, so setting the cookie function must be before any content is delivered to the browser. This limitation is the same as the header() function. Any cookies coming from the client will be automatically converted into a PHP variable. PHP obtains information headers and analyzes them, extracts the cookie name and turns it into a variable. Therefore, if you set cookies such as setcookie("mycookie","Cookies")php will automatically generate a variable named $mycookie and the value "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: represents the directory on the web server, and the default is the directory where the page is called is located.
DOMAIN: The domain name that can be used by cookies is the domain name of the called page by default. This domain must contain two ".", so if you specify your top-level domain, you must use "."
SECURE: If set to "1", it means that the cookie can only be remembered by the user's browser as a secure server.
Examples of use of cookies
Suppose we have such a site that needs to be registered, which automatically recognizes the user's identity and performs related operations: if it is a registered user, send information to him; if it is not a registered user, a link to the registration page will be displayed.
According to the above requirements, we first create a database to save the information of registered users: first name, last name, email address, and counter.
First, follow the steps below 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)
Then create a php page to check cookies against the database.
Since PHP can convert recognizable 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, we perform the following steps:
First, get the cookie value, use the exploit function to analyze it into different variables, add the counter, and set a new cookie:
$info = explode("&", $myCookies);
……
$count++;
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("myCookies",$CookieString, time()+3600); //Set cookies
Then use the html statement to output user information.
Finally, update the database with the new counter value.
If this cookie does not exist, we display a link to the registration page().
The following is the user registration page:
/* */
<form method="post" action="">
First Name:<input type="text" name="FirstName">
Last Name:<input type="text" name="LastName">
<input type="submit" value="registration">
</form>
Submit the information filled in by the user on the registration page to:
/* */
if ($FirstName and $LastName and $email) {
…//Query the user in the database if it exists
}
}else{
…//Error handling
}
The above program flow is as follows:
First check whether all the information is filled in as required. If not, return and re-enter.
If all the information is filled in, first, we will retrieve the user login details from the database.
mysql_connect() or die ("An error occurred 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 there is, it specifies the old information and uses the current information to create a new cookie. If the same user does not have a database login, create a new database login and create a new cookie.
Now use isset() function to check whether the user has a counter. If so, the counter will increase and create a new cookie:
$count++;//Increase the 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: No data should be output to the browser before calling the setcookie function, otherwise an error will occur.
How to implement cross-domain name cookies?
From the cookie specification, a cookie can only be used for one domain name. Therefore, if a cookie is set to a domain name in the browser, then this cookie will be invalid for other domain names.
Let’s talk about the implementation plan of cross-domain cookies:
Step 1: Create a preset script
Add the following code to the preset script (or appears in the functions that precede all scripts).
<?php
/*If the GET variable has been set and it is different from the cookie variable
* Use the get variable (update cookies)
*/
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 this code is run, a global variable 'sessionid' will be available for the script. It will save the sessionid value in the user's cookie, or the sessionid value sent via the GET request.
Step 2: Use variables for all cross domain references
Create a global configuration file to store the basic reference form of domain names that can be switched. For example, if we have the sum, then set it as follows:
<?php
$domains['domain1'] = "http:///-$sessionid-";
$domains['domain2'] = "http:///-$sessionid-";
?>
Let's write a code like this:
<?php
echo "Click <a href="", $domains['domain2'], "/contact/?email=yes">here</a> to contact us.";
?>
The above code will produce the following output:
Click <a href="http:///-66543afe6543asdf6asd-/contact/?email=yes">here</a> to contact us.
Here the sessionid has been inserted into the URL.
Step 3: Configure Apache
Now, let's configure Apache to rewrite this URL.
We need to
http:///-66543afe6543asdf6asd-/contact/
It became like this:
http:///contact/?sessionid=66543afe6543asdf6asd
And this kind of url:
http:///-66543afe6543asdf6asd-/contact/?email=yes
It became like this:
http:///contact/?email=yes&sessionid=66543afe6543asdf6asd
In order to achieve the above requirements, two virtual servers are simply configured as domain1 and domain2, as follows:
<VirtualHost ipaddress>
DocumentRoot /usr/local/www/domain1
ServerName
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
RewriteEngine on
RewriteRule ^/-(.*)-(.*?.*)$ $2&sessionid=$1 [L,R,QSA]
RewriteRule ^/-(.*)-(.*)$ $2?sessionid=$1 [L,R,QSA]
</VirtualHost>
These rewrite rules implement the requirements of rewriting the two URLs above.