本文將詳細介紹 PHP 中 Cookie 的基本操作,並實作一個 Cookie 隊列管理類,用於儲存有限數量的伺服器資訊,適用於遊戲伺服器選擇、最近瀏覽記錄等場景。
Cookie 是一種在用戶瀏覽器端儲存資料的機制,常用於追蹤與識別用戶。PHP 透過 HTTP 協定的標頭資訊發送 Cookie,因此 setcookie() 函數必須在任何輸出發送到瀏覽器之前呼叫,這點與 header() 函數的限制相同。
可以使用 setcookie() 或 setrawcookie() 函數設定 Cookie,也可直接發送 HTTP 標頭。以下是 setcookie() 的語法:
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]] )
參數說明:
簡單設定:
SetCookie("MyCookie", "Value of MyCookie");
帶有效期(1小時):
SetCookie("WithExpire", "Expire in 1 hour", time()+3600);
完整參數設定:
SetCookie("FullCookie", "Full cookie value", time()+3600, "/forum", ".phpuser.com", 1);
當需要儲存多筆資料並保持先進先出(FIFO)或最近使用優先的邏輯時,可實作隊列類。以下是核心程式碼:
class QueueSvc {
private $length;
private $server_arr;
public function __construct($length, $server_arr) {
$this->length = $length;
$this->server_arr = $server_arr;
}
public function getServerArr() {
return $this->server_arr;
}
public function set($server_name) {
$this->push($server_name);
}
private function push($server_name) {
// 移除重複項目
if ($this->isServerExist($server_name)) {
$this->removeRepeat($server_name);
} else {
// 隊列已滿,移除最舊項目
if ($this->isFull()) {
array_pop($this->server_arr);
}
}
// 初始化空陣列
if (empty($this->server_arr)) {
$this->server_arr = array();
}
// 加入隊列頭部
array_unshift($this->server_arr, $server_name);
}
private function isFull() {
return is_array($this->server_arr) && count($this->server_arr) >= $this->length;
}
private function isServerExist($server_name) {
return is_array($this->server_arr) && in_array($server_name, $this->server_arr);
}
private function removeRepeat($server_name) {
if (is_array($this->server_arr) && in_array($server_name, $this->server_arr)) {
foreach ($this->server_arr as $key => $value) {
if ($server_name == $value) {
$this->array_remove($this->server_arr, $key);
}
}
}
}
private function array_remove(&$arr, $offset) {
array_splice($arr, $offset, 1);
}
}
將隊列類與 Cookie 儲存結合:
require_once('queue_svc.php');
class CookieSvc {
const COOKIE_KEY = "GAME_SERVER";
const SEPARATE = "|";
const COOKIE_LENGTH = 2;
public function getCookieArr() {
$server_str = $_COOKIE[self::COOKIE_KEY] ?? '';
if ($server_str == '') {
return array();
}
return explode(self::SEPARATE, $server_str);
}
public function set($cookie_id) {
$server_arr = $this->getCookieArr();
if ($cookie_id !== false) {
$que = new QueueSvc(self::COOKIE_LENGTH, $server_arr);
$que->set($cookie_id);
$server_new = $que->getServerArr();
if (is_array($server_new)) {
$cookie_str = implode(self::SEPARATE, $server_new);
setcookie(self::COOKIE_KEY, $cookie_str, time()+3600, '/');
}
}
}
}
require_once("queue_svc.php");
require_once("cookie_svc.php");
$cookie_id = '4';
CookieSvc::set($cookie_id);
// 驗證結果
var_dump($_COOKIE);
ob_start() 緩衝輸出。希望本文能協助您掌握 PHP Cookie 操作與隊列管理的實作技巧。