PHP User Guide-cookies section

Source: Internet
Author: User
Keywords PHP User Guide-cookies section
Tags html header setcookie
PHP User Guide-cookies section

In this tutorial we will learn how to use PHP to process cookies, and I will try to make things as simple as possible to explain some of the practical applications of cookies.

What is a cookie and its role?
Cookies are generated by the Web server and present some information about the client. It is embedded in HTML information and is specified by the server, passing information between the client and server side
。 It is usually used for: User Web page personalization, counter, store the information of the browsing site and so on.

Cookies and PHP
It's fairly easy to use cookies in PHP. You can use the Setcookie function to set a cookie. Cookies are part of the HTTP header, so setting the cookie feature must precede any content being sent to the browser. This restriction is the same as the header () function. Any cookie from the client will automatically be converted to a PHP variable. PHP obtains the information header and parses it, extracts the cookie name and changes it into a variable. Therefore, if you set a cookie such as Setcookie ("MyCookie", "Wang");p HP will automatically generate a variable named $mycookie with a value of "Wang".

First let's review the Setcookie function syntax:
Setcookie (String cookiename, string cookievalue, int cookieexpiretime, path, domain, int secure);
PATH: Represents a directory on the Web server, default to the directory where the page is called
Domain:cookie the domain name that can be used, which defaults to 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", the cookie is only remembered by the server that the user's browser deems to be secure

Application:
For a site that needs to be registered, the user's identity will be automatically identified and sent to it, and if it is a stranger, you will be told to register first. We create a small database based on the information given below: First name, last name, 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), LastName varchar (40),
Email varchar (+), Count varchar (3));
Query OK, 0 rows affected (0.05 sec)
 
OK, now that we have a table that meets the requirements, we can build a PHP page to check cookies against the database.

####################### #index. php##################################
$info = Explode ("&", $Example);
$FirstName = $info [0];
$LastName = $info [1];
$email = $info [2];
$count = $info [3];
$count + +;

$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Example", $CookieString, Time () +3600); Set a new cookie

Echo  
<title>Wang Example</title>  
 
 

Hello $FirstName $LastName, this is your visit number: $count

 

Your Email address is: $email

 
 
";

Mysql_connect () or Die ("problem connecting to DataBase"); Update DB
$query = "Update info set count= $count where firstname= ' $FirstName ' and
Lastname= ' $LastName ' and email= ' $email ' ";
$result = Mysql_db_query ("Users", $query) or Die ("problems .... ");

}//end Existing Cookie instructions

else {//begin inctructions for no Cookie
echo "  
 
<title>Rafi ' s Cookie example</title> 
 
 
Click Here for Site registration
 
";
}//end No Cookie instructions
?>

Note: If you are using a remote MySQL server or UNIX server, you apply the following statement
mysql_connect ("Server", "username", "PassWord") or Die ("problem connecting to DataBase");

We want to check if a cookie with the specified name is transmitted in the HTML header, remember that PHP can convert the recognizable cookie to the corresponding variable, so we can check for a variable named "Example":
...
} else {
...
}
If this cookie exists, we add a counter and print the user information, and if this cookie does not exist, we recommend that the user register first
If a cookie exists, we perform the following steps:
$info = Explode ("&", $Example); Split the string to variables
$FirstName = $info [0];
$LastName = $info [1];
$email = $info [2];
$count = $info [3];
$count + +;

$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Example", $CookieString, Time () +3600); Setting a new cookie

Echo  
<title>Wang Example</title>  
 
 

Hello $FirstName $LastName, this is your visit number: $count

 

Your Email address is: $email

 
 
";

Mysql_connect () or Die ("problem connecting to DataBase"); Update DB
$query = "Update info set count= $count where firstname= ' $FirstName ' and
Lastname= ' $LastName ' and email= ' $email ' ";
$result = Mysql_db_query ("Users", $query) or Die ("problems .... ");

}//end Existing Cookie instructions
The above program has 3 main parts: First get the cookie value, use the EXPLODE function to separate variables, increase the counter, and set a new cookie. Then output the user information with an HTML statement. Finally, update the database with the new counter value.
If this cookie does not exist, the following program will be executed:
 
else {//begin inctructions for no Cookie
echo "  
 
<title>Rafi ' s Cookie example</title>  
 
 
Click Here for Site registration
 
";
}//end No Cookie instructions

The following reg.php a simple list of links to the registration page
############################ #reg. php#############################
 
 
 
<title>Registering the Site</title>  
 

 

Registering the site

 

 
 
 


Call another PHP file to parse this information after all the information has been committed
############################# #reg1. php####################################
if ($FirstName and $LastName and $email)
{
Mysql_connect () or Die ("problem connecting to DataBase");
$query = "SELECT * from info where firstname= ' $FirstName ' and
Lastname= ' $LastName ' and email= ' $email ' ";
$result = Mysql_db_query ("Users", $query);

$r =mysql_fetch_array ($result);
$count = $r ["Count"];

if (Isset ($count)) {
$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Example", $CookieString, Time () +3600);
echo "

User $FirstName $LastName already exists. Using the existing
Info.

";
echo "

Back to Main page ";
} else {
$count = ' 1 ';
$query = "INSERT INTO info values
(' $FirstName ', ' $LastName ', ' $email ', ' $count ');
$result = Mysql_db_query ("Users", $query);
$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Example", $CookieString, Time () +3600);
echo "Thank for registering.
";
}

} else {echo "Sorry, some information is missing. Go back and add all
The information "; }
?>
First check that all information is filled in as required, and if not, return to re-enter
if ($FirstName and $LastName and $email)
{
...
} else {echo "Sorry, some information is missing. Go back and add all
The information "; }
?>
If all information is filled out, the following will be performed:
 
Mysql_connect () or Die ("problem connecting to DataBase");
$query = "SELECT * from info where firstname= ' $FirstName ' and
Lastname= ' $LastName ' and email= ' $email ' ";
$result = Mysql_db_query ("Users", $query);

$r =mysql_fetch_array ($result);
$count = $r ["Count"];

if (Isset ($count)) {
$count + +;
$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Example", $CookieString, Time () +3600);
echo "

User $FirstName $LastName already exists. Using the existing
Info.

";
echo "

Back to Main page ";
} else {
$count = ' 1 '; New Visitor-set counter to 1.
$query = "INSERT INTO info values
(' $FirstName ', ' $LastName ', ' $email ', ' $count ');
$result = Mysql_db_query ("Users", $query);
$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Example", $CookieString, Time () +3600);
echo "Thank for registering.
";
This procedure does a few things: it checks whether the database has such a user (if not, that is, the cookie has been deleted), if there is, it specifies the old information, and uses the current information to build a new cookie, if the same user does not have a database login, create a database login, and build a new cookie.
First, we retrieve the user login details from the database
Mysql_connect () or Die ("problem connecting to DataBase");
$query = "SELECT * from info where firstname= ' $FirstName ' and
Lastname= ' $LastName ' and email= ' $email ' ";
$result = Mysql_db_query ("Users", $query);
$r =mysql_fetch_array ($result);
$count = $r ["Count"];

Now check if there is a counter for this user, using the Isset () function
 
if (Isset ($count)) {
...
} else {
...
}
Counter adds and creates a new cookie
$count + +; Increase counter
$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Example", $CookieString, Time () +3600);
echo "

User $FirstName $LastName already exists. Using the existing info.

";
echo "

Back to Main page ";
If you do not have a user counter, add a record to MySQL and set a cookie
Note: At any time, Setcookie to send any data to the browser before you get the error message

#####################################################
---Advance translation, there is no place, please qianjinok@china.com-------

  • 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.