Home > Backend Development > PHP Tutorial > PHP usage guide-cookies section

PHP usage guide-cookies section

WBOY
Release: 2016-08-08 09:34:03
Original
919 people have browsed it

PHP usage guide-cookies section

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

What are cookies and what do they do?
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".

Let us first review the setcookie function syntax:
setcookie(string CookieName, string CookieValue, int CookieExpireTime, path, domain, int secure);
PATH: represents the directory on the web server, the default is the directory where the called page is located
DOMAIN: The domain name that the cookie can use. The default 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 set to "1", it means that the cookie can only be remembered by servers that the user's browser considers to be secure

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 with the information given below: first name, last name, email address, visit counter.
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)

Okay, 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"
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 instructions 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 the specified name was sent in the html header. Remember, PHP can convert recognized cookies into corresponding variables, so we can check a variable called "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:
$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, increment 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 procedure will be executed:

else { //Begin instructions for no Cookie
echo "

Rafi's Cookie example


Click Here for Site Registration

";
} //End No Cookie instructions

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



Registering the Site



Registering the site









User Name: maxlength=20>
Last Name: maxlength=40>
email address: maxlength=40>






After all the information is submitted, another php file is called 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"; }  
?>  
首先检查所有的信息是否按要求填写,如果没有,返回重新输入
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放在输送任何资料到浏览器之前,否则得到错误信息

以上就介绍了PHP使用指南-cookies部分,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template