Table of Contents
Registering the site
Home Backend Development PHP Tutorial PHP用户指南-cookies部分

PHP用户指南-cookies部分

Jun 01, 2016 pm 02:31 PM

php用户指南-cookies部分

在这课教程我们将学习怎样利用 PHP 处理cookies,我将试着使事情尽可能简单地去解释cookies的一些实际应用。

什么是cookies及作用? 
cookies是由web服务器产生的并且存在客户端的一些信息。它嵌在html信息中,由服务器端指定,在客户端及服务器端间传递信息
。它通常用来:用户网页个性化,计数器,储存被浏览站点的信息等。

cookies和php
在 PHP中用cookies是相当容易的。可以使用setcookie函数设置一个cookie。cookie是 HTTP标头的一部分, 因此设置cookie功能必须在任何内容送到浏览器之前。这种限制与header()函数一样。任何从客户端传来的cookie将自动地转化成一个PHP变量。PHP取得信息头并分析, 提取cookie名并变成变量。因此,如果你设置cookie如setcookie("mycookie","wang");php将自动产生一个名为$mycookie,值为"wang"的变量.

先让我们复习一下setcookie函数语法:
setcookie(string CookieName, string CookieValue, int CookieExpireTime, path, domain, int secure);
PATH:表示web服务器上的目录,默认为被调用页面所在目录
DOMAIN:cookie可以使用的域名,默认为被调用页面的域名。这个域名必须包含两个".",所以如果你指定你的顶级域名,你必须用".mydomain.com"
SECURE:如果设为"1",表示cookie只能被用户的浏览器认为是安全的服务器所记住

应用:
对于一个需要注册的站点,将自动识别用户的身份,并发送给它信息,如果是陌生人,将告诉他请先注册。我们按下面给出的信息创建一个小型数 据库:名字(first name),姓(last name),email地址(email address),计数器(visit counter).
按下面步骤建表:

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)
 
好,现在有了符合要求的表,我们可以建一个php页面对照数据库检查cookies.

########################index.php##################################
if (isset($Example)) { //Begin instructions for existing Cookie 
$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); //设一新的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 
?>

注意:如果你用的是一个远程mysql服务器或unix服务器,你应用下面语句
mysql_connect ("server","username","passWord") or die ("Problem connecting to DataBase"); 

我们想检查是否一个被指定名字的cookie在html头部分传送,记住,php能转换可识别的cookie为相应的变量,所以我们能检查一个名为"Example" 的变量:
if (isset($Example)) { //Begin instructions for existing Cookie 
... 
} else { 
... 
}
如果这个cookie存在,我们将计数器加一,并打印用户信息,如果这个cookie不存在,我们建议用户先注册
如果cookie存在,我们执行下面步骤:
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
上面的程序有3个主要部分:首先取得cookie值,用explode函数分成不同的变量,增加计数器,并设一新cookie.接着用html语句输出用户信息。最后,用新的计数器值更新数据库。
如果这个cookie不存,下面的程序将被执行:
 
else { //Begin inctructions for no Cookie 
echo " 
 
Rafi's Cookie example 
 
 
Click Here for Site Registration 
 
"; 
} //End No Cookie instructions 

下面reg.php简单列出到注册页面的链接
#############################reg.php#############################
 
  
 
Registering the Site 
 

 

Registering the site

 

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


在所有的信息被提交后调用另一php文件分析这些信息
##############################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放在输送任何资料到浏览器之前,否则得到错误信息

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles