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" <html>
<title>wang example</title>
</head>
<body>
<p>Hello $FirstName $LastName, this is your visit number: $count</p>
<p>Your email address is: $email</p>
<body>
<html>";
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 "<html>
<head>
<Title>Rafi's Cookie example</title>
</head>
<body>
<a href="reg.php">Click Here for Site Registration</a>
</body>
</html>";
} //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" <html>
<title>wang example</title>
</head>
<body>
<p>Hello $FirstName $LastName, this is your visit number: $count</p>
<p>Your email address is: $email</p>
<body>
<html>";
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 "<html>
<head>
<Title>Rafi's Cookie example</title>
</head>
<body>
<a href="reg.php">Click Here for Site Registration</a>
</body>
</html>";
} //End No Cookie instructions
下面reg.php簡單列出到注冊頁面的鏈接
#############################reg.php#############################
<html>
<head><title>Registering the Site</title>
</head>
<body bgcolor=#ffffff>
<h1>Registering the site</h1>
<form method="post" action="reg1.php">
<table width=90% align=center>
<tr><td>User Name:</td><td><input type=text name='FirstName' size=20
maxlength=20></td></tr>
<tr><td>Last Name:</td><td><input type=text name='LastName' size=40
maxlength=40></td></tr>
<tr><td>email addrress:</td><td><input type=text name='email' size=40
maxlength=40></td></tr>
<tr><td></td><td><input type=submit value="Click to Register"></td></tr>
</table>
</form>
</body>
</html>
在所有的信息被提交後調用另一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 "<p>user $FirstName $LastName already exists. Using the existing
info.</p>";
echo "<p><a href="index.php">Back to Main Page</a>";
} 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.<br>";
}
} 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 "<p>user $FirstName $LastName already exists. Using the existing
info.</p>";
echo "<p><a href="index.php">Back to Main Page</a>";
} 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.<br>";
這段程序做了幾件工作:它檢查數據庫是否有這樣一個用戶(如果沒有,也就是說,這個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 "<p>user $FirstName $LastName already exists. Using the existing info.</p>";
echo "<p><a href="index.php">Back to Main Page</a>";
如果沒有一用戶計數器,在mysql中加一記錄,並設一cookie
注意:在任何時候,setcookie放在輸送任何資料到浏覽器之前,否則得到錯誤信息
#####################################################
---advance翻譯,有不恰之處,請
[email protected]