Cookies in PHP Guide

Source: Internet
Author: User
Tags count error handling explode header implement mysql variables variable
A summary of Cookie|cookies

cookie is a way for servers or scripts to maintain information on client workstations under the HTTP protocol. A cookie is a small file saved by a Web server in a user's browser that can contain information about a user, such as an identification number, a password, a user's way of shopping on a Web site, or the number of times a user accesses the site. The Web site can access cookie information whenever the user is linked to the server.

How to set up cookies?

In PHP, you can use the Setcookie function to set a cookie. Cookies are part of the HTTP header, so the cookie feature must be set before any content is sent to the browser. This limit is the same as the header () function. Any cookie from the client will automatically be converted into a PHP variable. PHP Gets the information header and analyzes it, extracts the cookie name and becomes a variable. Therefore, if you set cookies such as Setcookie ("MyCookie", "cookies") PHP will automatically generate a variable named $mycookie, 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 a directory on a Web server, which defaults to the directory where the page is called

The domain name that domain:cookie can use, default is the domain name of the called page. This domain name must contain two ".", so if you specify your top-level domain, you must use ". MyDomain.com"

secure: If set to "1", it means that the cookie can only be remembered by the server that the user's browser considers to be secure.

Cookies use examples

Let's say we have a site that needs to be registered, it automatically recognizes the identity of the user and carries out the relevant operation: if it is a registered user, send him the information; if it is not a registered user, a link to the registration page is displayed.

In accordance with the above requirements, we first create a database to save the registered user information: First name, surname (last name), e-mail address (email addresses), counters (visit counter).

First, follow the steps below to build the table:

mysql> CREATE database users;
query OK, 1 row affected (0.06 sec)
mysql> use users;
database changed
mysql> CREATE TABLE info (FirstName varchar, LastName varchar (), email varchar (), count varchar (3));
query OK, 0 rows affected (0.05 sec)



Then build a PHP page against the database to check cookies.

Because PHP can convert the recognizable cookie to the corresponding variable, we can check a variable named "Mycookies":

<? if (Isset ($myCookies)) {//If the cookie already exists
 ...
} else {//If cookie does not exist
 ...
}
?>

When a cookie is present, we perform the following steps:

First get the cookie value, use the Explode function to analyze different variables, add counters, and set a new cookie:

 $info = Explode ("&", $myCookies);
 ...
 $count + +;
 $CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
setcookie ("Mycookies", $CookieString, Time () +3600); Set cookies

Then use HTML statements 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 (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 that the user fills in the Register.php registration page submits to regok.php:

/* regok.php * *
if ($FirstName and $LastName and $email) {
......//queries whether the user exists in the database
}
}else{
......//Error Handling
£}




 The above program flow is as follows:

First check all the information is required to fill out, if not, return to re-enter

If all information is completed, first, we retrieve the user login details from the database

mysql_connect () or Die ("Connection database error!) ");
 $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, and if so, it specifies the old information and creates a new cookie with the current information, and if the same user does not have a database login, create a newly created database login and build a cookie.

Now use the Isset () function to check if the user has a counter, if there is a counter increase and create a new cookie:

 $count + +; Increase counter
 $CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
setcookie ("Mycookies", $CookieString, Time () +3600);

If you do not have a user counter, add a record in MySQL and set a cookie

Note: There should be no data output to the browser before calling the Setcookie function, otherwise an error will occur.

How do I implement a cross domain cookie?

From the cookie specification, a cookie can only be used for a domain name, so if a cookie is set in the browser for a domain name, then the cookie will not work for the other domain name.

Now let's talk about a cross domain cookie implementation scenario:

First step: Create a preset script

Add the following code to the Out-of-the-box script (or to a function that appears before all the scripts).

<?php
/* If the get variable is already set, and it is different from the cookie variable
* Use 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 this code is run, a global variable ' SessionID ' will be available for scripting. It will save the SessionID value in the user's cookie, or the SessionID value sent through a GET request.

Step two: Use variables for all cross domain references

Create a global configuration file that holds the basic reference form for domain names that can be toggled. For example, if we have domain1.com and domain2.com, the following settings are:

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

We write this piece of code:

<?php
echo "Click <a Href=" ", $domains [' domain2 '],"/contact/?email=yes ">here </a> to contact us."
? >

The code above will produce 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 Three: Configure Apache

Now, we're going to configure Apache to rewrite this URL.

We need to
http://www.domain2.com/-66543afe6543asdf6asd-/contact/
Become this:
Http://www.domain2.com/contact/?sessionid=66543afe6543asdf6asd
And this URL:
Http://www.domain2.com/-66543afe6543asdf6asd-/contact/?email=yes
Become this:
Http://www.domain2.com/contact/?email=yes&sessionid=66543afe6543asdf6asd

To achieve the above requirements, simply configure two virtual servers as domain1 and Domain2, as follows:

<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 overridden rules implement the requirements of the above two URL overrides.


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.