| 特性 | Cookie | Session |
|---|---|---|
| 儲存位置 | 客戶端瀏覽器 | 伺服器端 (檔案/Redis/DB) |
| 識別鍵 | 名稱/值對 | Session ID (SID) |
| 生命週期 | 可設定過期時間 | 瀏覽器關閉失效 (預設) 或配置 gc_maxlifetime |
| 容量限制 | 4KB / 個,約 300 個/域名 | 受伺服器儲存空間限制 |
| 安全性 | 可被竄改、竊取 | 資料在伺服器,相對安全 |
| 關聯方式 | 獨立 | 透過 Cookie/URL 傳遞 SID 關聯 |
session_start() → 檢查請求中是否攜帶 PHPSESSID (Cookie 或 GET 參數)$_SESSION;無 → 產生新 SID、建立空 Session$_SESSION 寫回儲存介質Set-Cookie: PHPSESSID=abc123; path=/; HttpOnly 種植/更新 Cookie<?php
// login.php
session_start();
if (isset($_POST['username'])) {
if ($_POST['username'] === 'admin' && $_POST['password'] === 'admin') {
$_SESSION['username'] = $_POST['username'];
echo '<a href="content.php">進入系統</a>';
} else {
echo '-1';
}
exit;
}
?>
<form method="post">
<input name="username"> <input type="password" name="password">
<button>登入</button>
</form>
<?php
// content.php
session_start();
echo isset($_SESSION['username']) ? 'login ok' : 'not login';
public class HttpUrlConnHelper {
private String sessionId = ""; // 手動維護 Cookie
public String request(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
if (!sessionId.isEmpty()) {
conn.addRequestProperty("Cookie", sessionId); // 關鍵:攜帶 SID
}
conn.connect();
return readResponse(conn);
}
public String login(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write("username=admin&password=admin".getBytes());
}
conn.connect();
// 關鍵:從回應頭提取 Set-Cookie
String setCookie = conn.getHeaderField("Set-Cookie");
if (setCookie != null) {
this.sessionId = setCookie.split(";")[0]; // 取 PHPSESSID=xxx
}
return readResponse(conn);
}
// ... readResponse 略
}
關鍵點:每次請求皆為獨立連線,必須手動管理 Cookie,否則每次請求都是新 Session。
public class HttpClientHelper {
private final CloseableHttpClient client = HttpClients.custom()
.setDefaultCookieStore(new BasicCookieStore()) // 自動管理 Cookie
.build();
public String request(String url) throws IOException {
HttpGet get = new HttpGet(url);
try (CloseableHttpResponse resp = client.execute(get)) {
return EntityUtils.toString(resp.getEntity());
}
}
public String login(String url) throws IOException {
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(Arrays.asList(
new BasicNameValuePair("username", "admin"),
new BasicNameValuePair("password", "admin")
), StandardCharsets.UTF_8));
try (CloseableHttpResponse resp = client.execute(post)) {
return EntityUtils.toString(resp.getEntity());
}
}
}
關鍵點:HttpClient 內建 CookieStore,自動處理 Set-Cookie / Cookie 頭,無需手動維護 Session ID。
<?php
// 必須在 session_start() 之前
ini_set('session.cookie_httponly', 1); // 防 XSS 竊取
ini_set('session.cookie_secure', 1); // 僅 HTTPS 傳輸 (正式環境)
ini_set('session.use_strict_mode', 1); // 拒絕未初始化的 SID
ini_set('session.cookie_samesite', 'Lax'); // 防 CSRF (PHP 7.3+)
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => '', // 當前域名
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
session_start();
// 防 Session Fixation
if (!isset($_SESSION['initiated'])) {
session_regenerate_id(true);
$_SESSION['initiated'] = true;
}
// 閒置超時銷毀 (30 分鐘)
if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > 1800) {
session_unset();
session_destroy();
}
$_SESSION['last_activity'] = time();
session.save_handler = redis,所有節點共享 Session 資料SessionHandlerInterface 寫入 MySQL/PostgreSQLHttpURLConnection),必須手動提取/攜帶 SIDHttpClient、瀏覽器、curl (含 -c/-b) 均具備自動 Cookie 管理能力HttpOnly、Secure、SameSite、strict_mode