Home  >  Article  >  Backend Development  >  PHP User Guide-Cookies Section_PHP Tutorial

PHP User Guide-Cookies Section_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 16:02:07719browse

PHP User Guide - Cookies Section

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

What are cookies and their functions?
Cookies are generated by the web server and contain some information about the client. It is embedded in html information, specified by the server, and transmits information between the client and the server
. It is usually used for: user web page personalization, counters, storing information about visited sites, etc.

Cookies and php
Using cookies in PHP is quite easy. A cookie can be set using the setcookie function. Cookies are part of the HTTP headers, so the cookie function must be set before any content is sent to the browser. This restriction is the same as the header() function. Any cookie passed from the client will automatically be converted into a PHP variable. PHP obtains the information header and analyzes it, extracts the cookie name and turns it into a variable. Therefore, if you set a cookie such as setcookie("mycookie","wang"); PHP will automatically generate a variable named $mycookie with a value of "wang".

First let us review the setcookie function syntax :
setcookie(string CookieName, string CookieValue, int CookieExpireTime, path, domain, int secure);
PATH: indicates the directory on the web server, the default is the directory where the called page is located
DOMAIN: Cookie can be used The domain name defaults to 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 set to "1", it means that the cookie can only be recognized by the user's browser Is a safe server remembered

Application:
For a site that requires registration, the user's identity will be automatically identified and information will be sent to it. If it is a stranger, he will be told to register first.We create a small database based on the information given below: first name, last name, email address, visit counter.
Follow the following steps to create a table:

mysql> create database users;
Query OK, 1 row affected (0.06 sec)

mysql> use users; varchar(20), LastName varchar(40),
email varchar(40), count varchar(3));
Query OK, 0 rows affected (0.05 sec)

Okay, now there are After obtaining a table that meets the requirements, we can build a php page to check the 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"
wang example


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 " 
 
Rafi's Cookie example 
 
 
Click Here for Site Registration

";
} //End No Cookie instructions
?>

Note: If you are using a remote mysql server or unix server, you should use the following statement
mysql_connect ("server", "username", "password") or die ("Problem connecting to DataBase");

We want to check if a cookie with a specified name is sent in the html header. Remember, PHP can convert identifiable cookies into corresponding variables, so we can check A variable named "Example":
...
} else {
...
}
If this cookie exists, we will add one to the counter and print the user information. If this cookie does not exist, we recommend that the user register first
If the cookie exists, we perform the following steps:
< ? if (isset($Example)) { //Begin instructions for existing Cookie
$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"
wang example


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 three main parts: first obtain the cookie value, use the explode function to divide it into different variables, increase the counter, and set a new cookie. Then use html statements to output user information. Finally, the database is updated with the new counter value.
If this cookie does not exist, the following program will be executed:

else { //Begin incstructions for no Cookie                                                                                                              Rafi's Cookie example



";
} //End No Cookie instructions

The following reg.php simply lists the link to the registration page
# ############################reg.php################### ##########



Registering the Site



Registering the site





=submit value="Click to Register">
User Name:maxlength=20>
Last Name:maxlength=40>
email address:maxlength=40>


/html>


After all the information is submitted, call another php file to analyze the information
################### ##########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 you for registering.
";
}

} else { echo "Sorry, some information is missing. Please go back and add all
the information"; }
?>
First check whether all the information is filled in as required. If not, go back and re-enter
if ($FirstName and $LastName and $email)
{
...
} else { echo "Sorry, some information is missing. Please go back and add all
the information "; }  
?>
如果所有信息填好,将执行下面:

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 you for registering.
";  
这段程序做了几件工作:它检查数据库是否有这样一个用户(如果没有,也就是说,这个cookie已被删除),如果有,它指定旧的信息,并用当前的信息建一新的cookie,如果同一用户没有数据库登录,新建一数据库登录,并建一新的cookie.
首先,我们从数据库中取回用户登录详细资料
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"];

现在检查是否有一计数器为这用户,利用isset()函数

if (isset($count)) {  
...  
} else {  
...  
}  
计数器增加并新建一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";
如果没有一用户计数器,在mysql中加一记录,并设一cookie
注意:在任何时候,setcookie放在输送任何资料到浏览器之前,否则得到错误信息

#####################################################
---advance翻译,有不恰之处,请qianjinok@china.com-------

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/316640.htmlTechArticlePHP用户指南-cookies部分 在这课教程我们将学习怎样利用 PHP 处理cookies,我将试着使事情尽可能简单地去解释cookies的一些实际应用。 什么是c...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn