setcookie

setcookie(string $name, string $value = "", array $expires = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): bool

登记 Set-Cookie 响应头(过期/路径/域/HttpOnly/Secure 均为头参数);必须在任何输出之前调用。

C C23

C23
#include <stdio.h>

int main(void) {
    /* CGI/自写 HTTP 服务器:手写 Set-Cookie 头(PHP setcookie 帮你做的事) */
    /* 属性顺序约定俗成:值 → Path → HttpOnly → Secure */
    printf("set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure\n");
    /* 删除 Cookie = Max-Age=0 */
    printf("del: Set-Cookie: tracker=; Path=/; Max-Age=0\n");
    return 0;
}
输出
set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure
del: Set-Cookie: tracker=; Path=/; Max-Age=0

C++ C++26

C++26
#include <iostream>

int main() {
    // CGI/自写 HTTP 服务器:手写 Set-Cookie 头(PHP setcookie 帮你做的事)
    // 属性顺序约定俗成:值 → Path → HttpOnly → Secure
    std::cout << "set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure\n";
    // 删除 Cookie = Max-Age=0
    std::cout << "del: Set-Cookie: tracker=; Path=/; Max-Age=0\n";
    return 0;
}
输出
set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure
del: Set-Cookie: tracker=; Path=/; Max-Age=0

C# v11.0.100

v11.0.100
// ASP.NET 的 Cookie API 在框架层(IResponseCookies);控制台手写 Set-Cookie 头字符串
// 属性顺序约定俗成:值 → Path → HttpOnly → Secure
Console.WriteLine("set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure");
// 删除 Cookie = Max-Age=0
Console.WriteLine("del: Set-Cookie: tracker=; Path=/; Max-Age=0");
输出
set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure
del: Set-Cookie: tracker=; Path=/; Max-Age=0

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	// 标准库 net/http:http.SetCookie 组装并写入 Set-Cookie 头(httptest 记录器演示,替代真实 ResponseWriter)
	rec := httptest.NewRecorder()
	http.SetCookie(rec, &http.Cookie{
		Name: "theme", Value: "dark", Path: "/", HttpOnly: true, Secure: true,
	})
	fmt.Println("set: Set-Cookie:", rec.Header().Get("Set-Cookie"))
	// 删除 Cookie:MaxAge 为负即「立即过期」(输出 Max-Age=0)
	rec2 := httptest.NewRecorder()
	http.SetCookie(rec2, &http.Cookie{Name: "tracker", Path: "/", MaxAge: -1})
	fmt.Println("del: Set-Cookie:", rec2.Header().Get("Set-Cookie"))
}
输出
set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure
del: Set-Cookie: tracker=; Path=/; Max-Age=0

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        // Servlet 的 Cookie/响应 API 不在标准库(jakarta.servlet.http.Cookie 是框架层);手写 Set-Cookie 头
        // 属性顺序约定俗成:值 → Path → HttpOnly → Secure
        System.out.println("set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure");
        // 删除 Cookie = Max-Age=0
        System.out.println("del: Set-Cookie: tracker=; Path=/; Max-Age=0");
    }
}
输出
set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure
del: Set-Cookie: tracker=; Path=/; Max-Age=0

JavaScript v26.13.1

v26.13.1
// Node 无内置 Cookie API(框架层 cookie/res.cookie 才是真等价物);手写 Set-Cookie 头字符串
// 属性顺序约定俗成:值 → Path → HttpOnly → Secure;HttpOnly 防 JS 读取,Secure 限 HTTPS
const setLine = "Set-Cookie: theme=dark; Path=/; HttpOnly; Secure";
console.log("set:", setLine);
// 删除 Cookie = 过期时间放到过去(Max-Age=0)
const delLine = "Set-Cookie: tracker=; Path=/; Max-Age=0";
console.log("del:", delLine);
输出
set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure
del: Set-Cookie: tracker=; Path=/; Max-Age=0

PHP v8.6.0

v8.6.0
// setcookie:登记 Set-Cookie 响应头;PHP 7.3+ 推荐选项数组风格(替代 7.2- 的一长串位置参数)
// 注意:必须在任何输出之前调用(头已发送后返回 false)
$okSet = setcookie("theme", "dark", [
    "path" => "/",
    "httponly" => true,   // JS 不可读(防 XSS 窃取)
    "secure" => true,     // 仅 HTTPS 传输
]);
// 删除 Cookie = 过期时间放到过去(浏览器收到即删同名 Cookie)
$okDel = setcookie("tracker", "", ["expires" => time() - 3600]);
echo "setcookie theme: ", var_export($okSet, true), "\n";
echo "setcookie tracker: ", var_export($okDel, true), "\n";
// CLI SAPI 不真正发送头:headers_list() 恒为空(Web 下这里会出现两条 Set-Cookie)
echo "headers in CLI: ", count(headers_list()), "\n";
// 读取方视角:$_COOKIE 由请求头 Cookie: 填充(CLI 手动模拟一次)
$_COOKIE["theme"] = "dark";
echo $_COOKIE["theme"], "\n";
输出
setcookie theme: true
setcookie tracker: true
headers in CLI: 0
dark

Python v3.15.2

v3.15.2
from http.cookies import SimpleCookie

# 手发 Set-Cookie 头对照:标准库 http.cookies(BaseHTTPServer 场景手动写入响应头)
# PHP 的 setcookie 是「框架替你发头」;Python 标准库只给序列化器,头要自己写
# 注意 SimpleCookie 的属性输出顺序是它的固定顺序(HttpOnly 在 Path 前)
c = SimpleCookie()
c["theme"] = "dark"
c["theme"]["path"] = "/"
c["theme"]["httponly"] = True
c["theme"]["secure"] = True
print("set:", c.output())
# 删除 Cookie = 过期时间放到过去(max-age=0)
d = SimpleCookie()
d["tracker"] = ""
d["tracker"]["path"] = "/"
d["tracker"]["max-age"] = 0
print("del:", d.output())
输出
set: Set-Cookie: theme=dark; HttpOnly; Path=/; Secure
del: Set-Cookie: tracker=""; Max-Age=0; Path=/

Rust v1.99.1

v1.99.1
fn main() {
    // 标准库无 Cookie 设施(实战用 cookie crate 或框架提取器);手写 Set-Cookie 头字符串
    // 属性顺序约定俗成:值 → Path → HttpOnly → Secure
    println!("set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure");
    // 删除 Cookie = Max-Age=0
    println!("del: Set-Cookie: tracker=; Path=/; Max-Age=0");
}
输出
set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure
del: Set-Cookie: tracker=; Path=/; Max-Age=0

TypeScript v26.13.1

v26.13.1
// Node 无内置 Cookie API(框架层 cookie/res.cookie 才是真等价物);手写 Set-Cookie 头字符串
// 属性顺序约定俗成:值 → Path → HttpOnly → Secure;HttpOnly 防 JS 读取,Secure 限 HTTPS
const setLine: string = "Set-Cookie: theme=dark; Path=/; HttpOnly; Secure";
console.log(`set: ${setLine}`);
// 删除 Cookie = 过期时间放到过去(Max-Age=0)
const delLine: string = "Set-Cookie: tracker=; Path=/; Max-Age=0";
console.log(`del: ${delLine}`);
输出
set: Set-Cookie: theme=dark; Path=/; HttpOnly; Secure
del: Set-Cookie: tracker=; Path=/; Max-Age=0

语言差异说明

C:CGI 层手写 Set-Cookie: 头(printf 输出到响应头区),头后必须跟 \r\n\r\n 再出正文。

C++:同 C。

C#:框架层是 ASP.NET 的 IResponseCookies.Append;标准库 System.Net.Cookie 只是数据结构,序列化到头仍是框架的事;控制台手写字符串。

Go:标准库 net/http 内置——http.SetCookie(w, &http.Cookie{...}) 完整对齐 PHP 语义(Path/Domain/MaxAge/HttpOnly/Secure/SameSite);删除 Cookie 惯用 MaxAge: -1。

Java:标准库 java.net.HttpCookie 偏客户端解析;服务端下发是 Servlet response.addCookie(框架层);示例手写头。

JavaScript:Node 无内置——手写头字符串或框架 res.cookie(express);cookie-parser 负责读方向。

PHP:setcookie 是唯一惯用写法,等价于拼 header("Set-Cookie: ...");过期参数 0 = 会话 Cookie(随浏览器关闭消失)、时间在过去 = 删除;HttpOnly 防 XSS 读取、Secure 限 HTTPS、SameSite 防 CSRF(7.3+ 选项数组支持);在任何输出之后调用返回 false(头已发送)。

Python:标准库 http.cookies.SimpleCookie 序列化 Set-Cookie(注意其属性顺序固定:HttpOnly 在 Path 前);Web 框架里是 resp.set_cookie。

Rust:标准库无——cookie crate 或框架的 Cookie 提取器/构造器。

TypeScript:同 JavaScript。