搜尋
首頁後端開發php教程PHP用户指南-cookies部分

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

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具