PHP中cookies指南
Jun 21, 2016 am 09:14 AMcookie|cookies
綜述
Cookie是在HTTP協(xié)議下,服務(wù)器或腳本可以維護(hù)客戶工作站上信息的一種方式。Cookie是由Web服務(wù)器保存在用戶瀏覽器上的小文件,它可以包含有關(guān)用戶的信息(如身份識(shí)別號(hào)碼、密碼、用戶在Web站點(diǎn)購(gòu)物的方式或用戶訪問(wèn)該站點(diǎn)的次數(shù))。無(wú)論何時(shí)用戶鏈接到服務(wù)器,Web站點(diǎn)都可以訪問(wèn)Cookie信息。
怎樣設(shè)置cookies?
在PHP中可以使用setcookie函數(shù)設(shè)置一個(gè)cookie。cookie是 HTTP標(biāo)頭的一部分, 因此設(shè)置cookie功能必須在任何內(nèi)容送到瀏覽器之前。這種限制與header()函數(shù)一樣。任何從客戶端傳來(lái)的cookie將自動(dòng)地轉(zhuǎn)化成一個(gè)PHP變量。PHP取得信息頭并分析, 提取cookie名并變成變量。因此,如果設(shè)置cookie如setcookie("mycookie","Cookies")php將自動(dòng)產(chǎn)生一個(gè)名為$mycookie,值為"Cookies"的變量。
我們來(lái)看一下setcookie函數(shù)語(yǔ)法:
init setcookie(string CookieName,string CookieValue,int CookieExpireTime,path,domain,int secure);
參數(shù)說(shuō)明:
PATH:表示web服務(wù)器上的目錄,默認(rèn)為被調(diào)用頁(yè)面所在目錄
DOMAIN:cookie可以使用的域名,默認(rèn)為被調(diào)用頁(yè)面的域名。這個(gè)域名必須包含兩個(gè)".",所以如果你指定你的頂級(jí)域名,你必須用".mydomain.com"
SECURE:如果設(shè)為"1",表示cookie只能被用戶的瀏覽器認(rèn)為是安全的服務(wù)器所記住.
cookies使用舉例
假設(shè)我們有這樣一個(gè)需要注冊(cè)的站點(diǎn),它自動(dòng)識(shí)別用戶的身份并進(jìn)行相關(guān)的操作:如果是已經(jīng)注冊(cè)的用戶,發(fā)送給他信息;如果不是已經(jīng)注冊(cè)的用戶,則顯示一個(gè)注冊(cè)頁(yè)面的鏈接。
按照上面的要求,我們先創(chuàng)建數(shù)據(jù)庫(kù)用來(lái)保存注冊(cè)用戶的信息:名字(first name),姓(last name),Email地址(email address),計(jì)數(shù)器(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)
然后建一個(gè)php頁(yè)面對(duì)照數(shù)據(jù)庫(kù)檢查cookies。
由于php能轉(zhuǎn)換可識(shí)別的cookie為相應(yīng)的變量,所以我們能檢查一個(gè)名為"myCookies" 的變量:
<? if (isset($myCookies)) { // 如果Cookie已經(jīng)存在
……
} else { //如果Cookie不存在
……
}
?>
當(dāng)cookie存在時(shí),我們執(zhí)行下面步驟:
首先取得cookie值,用explode函數(shù)分析成不同的變量,增加計(jì)數(shù)器,并設(shè)一個(gè)新cookie:
$info = explode("&", $myCookies);
……
$count++;
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("myCookies",$CookieString, time()+3600); //設(shè)置cookie
接著用html語(yǔ)句輸出用戶信息。
最后,用新的計(jì)數(shù)器值更新數(shù)據(jù)庫(kù)。
如果這個(gè)cookie不存在,我們顯示一個(gè)注冊(cè)頁(yè)(register.php)的鏈接。
下面的register.php是用戶注冊(cè)頁(yè)面:
/* register.php */
<form method="post" action="regOK.php">
First Name:<input type="text" name="FirstName">
Last Name:<input type="text" name="LastName">
<input type="submit" value="注冊(cè)">
</form>
用戶在register.php注冊(cè)頁(yè)面填寫(xiě)的信息提交給regOK.php:
/* regOK.php */
if ($FirstName and $LastName and $email) {
……//在數(shù)據(jù)庫(kù)查詢用戶是否存在
}
}else{
……//錯(cuò)誤處理
}
上面的程序流程如下:
首先檢查所有的信息是否按要求填寫(xiě),如果沒(méi)有,返回重新輸入
如果所有信息填好,首先,我們從數(shù)據(jù)庫(kù)中取回用戶登錄詳細(xì)資料
mysql_connect() or die ("連接數(shù)據(jù)庫(kù)出現(xiàn)錯(cuò)誤!");
$query="select * from info where FirstName='$FirstName' and LastName='$LastName' and email='$email'";
$result = mysql_db_query("users", $query);
$info=mysql_fetch_array($result);
$count=$info["count"];
檢查數(shù)據(jù)庫(kù)是否有這樣一個(gè)用戶,如果有,它指定舊的信息,并用當(dāng)前的信息建一新的cookie,如果同一用戶沒(méi)有數(shù)據(jù)庫(kù)登錄,新建一數(shù)據(jù)庫(kù)登錄,并建一新的cookie。
現(xiàn)在利用isset()函數(shù)檢查用戶是否有計(jì)數(shù)器,如果有則計(jì)數(shù)器增加并且建立一個(gè)新的cookie:
$count++; //增加計(jì)數(shù)器
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("myCookies",$CookieString, time()+3600);
如果沒(méi)有一用戶計(jì)數(shù)器,在mysql中加一記錄,并設(shè)一cookie
注意:調(diào)用setcookie函數(shù)之前應(yīng)該沒(méi)有任何數(shù)據(jù)輸出倒瀏覽器,否則將會(huì)出現(xiàn)錯(cuò)誤。
如何實(shí)現(xiàn)跨域名Cookie?
從Cookie規(guī)范上說(shuō),一個(gè)cookie只能用于一個(gè)域名,因此,如果在瀏覽器中對(duì)一個(gè)域名設(shè)置了一個(gè)cookie,那么這個(gè)cookie對(duì)于其它的域名將無(wú)效。
下面我們來(lái)談一個(gè)跨域名cookie的實(shí)現(xiàn)方案:
第一步:創(chuàng)建預(yù)置腳本
將下面的代碼加到預(yù)置腳本中(或出現(xiàn)在所有腳本之前的函數(shù)中)。
<?php
/*如果GET變量已經(jīng)設(shè)置了,并且它與cookie變量不同
*則使用get變量(更新cookie)
*/
global $HTTP_COOKIE_VARS, $HTTP_GET_VARS;
if (isset($sessionid) && isset($HTTP_GET_VARS['sessionid']) && ($HTTP_COOKIE_VARS['sessionid'] != $HTTP_GET_VARS['sessionid'])) {
SetCookie('sessionid', $HTTP_GET_VARS['sessionid'], 0, '/', '');
$HTTP_COOKIE_VARS['sessionid'] = $HTTP_GET_VARS['sessionid'];
$sessionid = $HTTP_GET_VARS['sessionid'];
}
?>
這個(gè)代碼運(yùn)行之后,一個(gè)全局變量'sessionid'將可以用于腳本。它將保存用戶的cookie中的sessionid值,或者是通過(guò)GET請(qǐng)求發(fā)來(lái)的sessionid值。
第二步:為所有的交叉域名引用使用變量
創(chuàng)建一個(gè)全局的配置文件,用于存放可以進(jìn)行切換的域名的基本引用形式。例如,如果我們擁有domain1.com和domain2.com,則如下設(shè)置:
<?php
$domains['domain1'] = "http://www.domain1.com/-$sessionid-";
$domains['domain2'] = "http://www.domain2.com/-$sessionid-";
?>
我們寫(xiě)這樣一段代碼:
?。?php
echo "Click <a href="", $domains['domain2'], "/contact/?email=yes">here</a> to contact us.";
?>
上面的代碼將產(chǎn)生如下的輸出:
Click <a >here</a> to contact us.
在這里sessionid已經(jīng)被插入到URL中去了。
第三步:配置Apache
現(xiàn)在,我們來(lái)配置Apache來(lái)重寫(xiě)這個(gè)URL。
我們需要將
http://www.domain2.com/-66543afe6543asdf6asd-/contact/
變成這樣:
http://www.domain2.com/contact/?sessionid=66543afe6543asdf6asd
并且這種url:
http://www.domain2.com/-66543afe6543asdf6asd-/contact/?email=yes
變成這樣:
http://www.domain2.com/contact/?email=yes&sessionid=66543afe6543asdf6asd
為了實(shí)現(xiàn)上面的要求,簡(jiǎn)單地配置兩個(gè)虛擬服務(wù)器,作為domain1和domain2,如下操作:
?。糣irtualHost ipaddress>
DocumentRoot /usr/local/www/domain1
ServerName www.domain1.com
RewriteEngine on
RewriteRule ^/-(.*)-(.*?.*)$ $2&sessionid=$1 [L,R,QSA]
RewriteRule ^/-(.*)-(.*)$ $2?sessionid=$1 [L,R,QSA]
?。?VirtualHost>
<VirtualHost ipaddress>
DocumentRoot /usr/local/www/domain2
ServerName www.domain2.com
RewriteEngine on
RewriteRule ^/-(.*)-(.*?.*)$ $2&sessionid=$1 [L,R,QSA]
RewriteRule ^/-(.*)-(.*)$ $2?sessionid=$1 [L,R,QSA]
?。?VirtualHost>
這些重寫(xiě)的規(guī)則實(shí)現(xiàn)了上面兩個(gè)URL重寫(xiě)的要求。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

Explore the causes and solutions of HTTP status code 404 Introduction: In the process of browsing the web, we often encounter HTTP status code 404. This status code indicates that the server was unable to find the requested resource. In this article, we will explore the causes of HTTP status code 404 and share some solutions. 1. Reasons for HTTP status code 404: 1.1 Resource does not exist: The most common reason is that the requested resource does not exist on the server. This may be caused by the file being accidentally deleted, incorrectly named, incorrectly pathed, etc.

How to implement HTTP streaming in C++? Create an SSL stream socket using Boost.Asio and the asiohttps client library. Connect to the server and send an HTTP request. Receive HTTP response headers and print them. Receives the HTTP response body and prints it.

In our daily use of computers and the Internet, we are often exposed to cookies. A cookie is a small text file that saves records of our visits to the website, preferences and other information. This information may be used by the website to better serve us. But sometimes, we need to find cookie information to find the content we want. So how do we find cookies in the browser? First, we need to understand where the cookie exists. in browser
