session_create_id
session_create_id(string $prefix = ""): string|false
生成无碰撞的会话 ID(字符集 [0-9a-zA-Z,-],可加前缀);ID 格式(长度/字符集)由 php.ini 决定。会话激活时带碰撞检查,用户级 save handler 的配套工具。
C C23
#include <stdio.h>
#include <string.h>
#include <time.h>
/* C 标准库没有 CSPRNG:真实实现会用 getrandom/arc4random;
时间+计数器派生的十六进制 ID 展示格式契约(32 位十六进制、可加前缀) */
static int counter = 0;
static void make_id(char out[33]) {
unsigned long long t = (unsigned long long)time(NULL) * 1000UL + (unsigned long long)(++counter);
snprintf(out, 33, "%032llx", t);
}
int main(void) {
char idA[33], idB_body[33];
make_id(idA);
int fmtOk = strlen(idA) == 32 && strspn(idA, "0123456789abcdef") == 32;
make_id(idB_body);
char prefixed[40];
snprintf(prefixed, sizeof prefixed, "user-%s", idB_body);
printf("format ok: %s\n", fmtOk ? "true" : "false");
printf("prefix ok: %s\n", strncmp(prefixed, "user-", 5) == 0 ? "true" : "false");
printf("length ok: %s\n", strlen(prefixed) - 5 == 32 ? "true" : "false");
printf("distinct: %s\n", strcmp(idA, idB_body) != 0 ? "true" : "false");
return 0;
}
format ok: true prefix ok: true length ok: true distinct: true
C++ C++26
#include <chrono>
#include <iostream>
#include <cstdio>
#include <string>
static std::string hexId() {
/* std 没有 CSPRNG:真实代码应使用加密随机数;时间派生的十六进制 ID 展示格式契约(32 位十六进制) */
const auto now = std::chrono::system_clock::now().time_since_epoch().count();
char buf[33];
std::snprintf(buf, sizeof buf, "%032llx", (unsigned long long)now);
return std::string(buf);
}
int main() {
const std::string id = hexId();
const std::string prefixed = "user-" + id;
std::cout << "format ok: " << (id.size() == 32 ? "true" : "false") << "\n";
std::cout << "prefix ok: " << (prefixed.rfind("user-", 0) == 0 ? "true" : "false") << "\n";
std::cout << "length ok: " << (prefixed.size() - 5 == 32 ? "true" : "false") << "\n";
std::cout << "distinct: " << (id != hexId() ? "true" : "false") << "\n";
return 0;
}
format ok: true prefix ok: true length ok: true distinct: true
C# v11.0.100
// Guid.NewGuid() 是 .NET 对 PHP 无碰撞 ID 生成器的对应物
string id = System.Guid.NewGuid().ToString("N"); // 32 位十六进制、无连字符——与 PHP 默认 ID 同形态
string prefixed = "user-" + id; // 前缀对应 session_create_id("user-")
bool fmtOk = id.Length == 32 && System.Text.RegularExpressions.Regex.IsMatch(id, "^[0-9a-f]+$");
Console.WriteLine("format ok: " + fmtOk);
Console.WriteLine("prefix ok: " + prefixed.StartsWith("user-"));
Console.WriteLine("length ok: " + (prefixed.Length - 5 == 32));
Console.WriteLine("distinct: " + (id != System.Guid.NewGuid().ToString("N")));
format ok: True prefix ok: True length ok: True distinct: True
Go v1.27.4
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"strings"
)
func newId(prefix string) string {
// crypto/rand 是 PHP 会话 ID 生成器的 CSPRNG 对应物
b := make([]byte, 16)
rand.Read(b) // 16 字节 → 32 位十六进制,与 PHP 默认 ID 同形态
return prefix + hex.EncodeToString(b)
}
func main() {
id := newId("")
prefixed := newId("user-")
body := strings.TrimPrefix(prefixed, "user-")
fmt.Println("format ok:", len(id) == 32 && strings.Trim(id, "0123456789abcdef") == "")
fmt.Println("prefix ok:", strings.HasPrefix(prefixed, "user-"))
fmt.Println("length ok:", len(body) == 32)
fmt.Println("distinct:", id != body)
}
format ok: true prefix ok: true length ok: true distinct: true
Java v27.0.1
import java.util.UUID;
public class Main {
public static void main(String[] args) {
// UUID.randomUUID() 是 PHP ID 生成器的 CSPRNG 对应物
String id = UUID.randomUUID().toString(); // 36 字符含连字符
String prefixed = "user-" + id; // 前缀对应 session_create_id("user-")
boolean fmtOk = id.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
System.out.println("format ok: " + fmtOk);
System.out.println("prefix ok: " + prefixed.startsWith("user-"));
System.out.println("length ok: " + (prefixed.length() - 5 == 36));
System.out.println("distinct: " + !id.equals(UUID.randomUUID().toString()));
}
}
format ok: true prefix ok: true length ok: true distinct: true
JavaScript v26.13.1
const { randomUUID } = require("node:crypto");
// randomUUID 是 PHP 会话 ID 生成器的 CSPRNG 对应物
const id = randomUUID(); // 36 字符,UUID 格式
const prefixed = "user-" + id; // 前缀对应 session_create_id("user-")
const fmtOk = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);
console.log("format ok:", fmtOk);
console.log("prefix ok:", prefixed.startsWith("user-"));
console.log("length ok:", prefixed.length - 5 === 36);
console.log("distinct:", id !== randomUUID());
format ok: true prefix ok: true length ok: true distinct: true
PHP v8.6.0
// session_create_id:为用户级 save handler 生成无碰撞的会话 ID
// ID 的字符集与长度由 php.ini 决定;前缀只允许 [a-zA-Z0-9,-]
ini_set("session.save_path", sys_get_temp_dir());
$idA = session_create_id(); // 无激活会话:跳过碰撞检查
$idB = session_create_id("user-"); // 带前缀变体
$fmt = is_string($idA) && preg_match('/^[0-9a-zA-Z,-]+$/', $idA) === 1;
$pre = is_string($idB) && str_starts_with($idB, "user-");
$len = strlen($idB) - strlen("user-") === strlen($idA);
$dis = $idA !== substr($idB, strlen("user-"));
session_start();
$idC = session_create_id(); // 会话激活时:对照存储做碰撞检查
$act = is_string($idC) && strlen($idC) === strlen($idA);
session_write_close();
echo "format ok: ", var_export($fmt, true), "\n";
echo "prefix ok: ", var_export($pre, true), "\n";
echo "length ok: ", var_export($len, true), "\n";
echo "active ok: ", var_export($act, true), "\n";
echo "distinct: ", var_export($dis && $idA !== $idC, true);
format ok: true prefix ok: true length ok: true active ok: true distinct: true
Python v3.15.2
import secrets
# secrets 是 PHP 会话 ID 生成器的 CSPRNG 对应物;
# token_hex(16) 产出 32 位十六进制——与 PHP 默认 ID 同形态
id_a = secrets.token_hex(16)
id_b = "user-" + secrets.token_hex(16) # 前缀对应 session_create_id("user-")
print("format ok:", len(id_a) == 32 and all(ch in "0123456789abcdef" for ch in id_a))
print("prefix ok:", id_b.startswith("user-"))
print("length ok:", len(id_b) - len("user-") == 32)
print("distinct:", id_a != id_b[len("user-"):])
format ok: True prefix ok: True length ok: True distinct: True
Rust v1.99.1
use std::time::{SystemTime, UNIX_EPOCH};
fn hex_id() -> String {
/* std 没有 CSPRNG(真实代码用 rand/uuid crate);时间派生的十六进制 ID 展示格式契约(32 位十六进制) */
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
format!("{:032x}", nanos)
}
fn main() {
let id = hex_id();
let prefixed = format!("user-{}", id);
println!("format ok: {}", id.len() == 32 && id.chars().all(|c| c.is_ascii_hexdigit()));
println!("prefix ok: {}", prefixed.starts_with("user-"));
println!("length ok: {}", prefixed.len() - 5 == 32);
println!("distinct: {}", id != hex_id());
}
format ok: true prefix ok: true length ok: true distinct: true
TypeScript v26.13.1
import { randomUUID } from "node:crypto";
// randomUUID 是 PHP 会话 ID 生成器的 CSPRNG 对应物
const id: string = randomUUID(); // 36 字符,UUID 格式
const prefixed: string = "user-" + id; // 前缀对应 session_create_id("user-")
const fmtOk: boolean = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);
console.log("format ok:", fmtOk);
console.log("prefix ok:", prefixed.startsWith("user-"));
console.log("length ok:", prefixed.length - 5 === 36);
console.log("distinct:", id !== randomUUID());
format ok: true prefix ok: true length ok: true distinct: true
语言差异说明
C:标准库无 CSPRNG——实战用平台 API(Linux getrandom、BSD/macOS arc4random_buf)或读 /dev/urandom;示例用时间派生值只演示格式契约,绝不能用于生产会话。
C++:同 C(chrono 时间戳演示格式);真实实现用 OpenSSL RAND_bytes 或系统 CSPRNG。
C#:Guid.NewGuid().ToString("N") 与 PHP 默认 ID 同为 32 位十六进制(CSPRNG 支持);格式化 "D" 则是带连字符的 36 字符。
Go:crypto/rand + hex.EncodeToString 16 字节 → 32 位十六进制,形态与 PHP 默认 ID 一致;注意 rand.Read 的错误要检查。
Java:UUID.randomUUID()(SecureRandom 支持)是标准做法;128 位熵优于 PHP 默认的 32×4=128 bit。
JavaScript:crypto.randomUUID()(Node ≥14.17 / 浏览器 Web Crypto);与 PHP 的差异是 UUID 格式而非裸十六进制——碰撞概率同为可忽略。
PHP:session_create_id 的价值在「激活会话下生成时对照存储查碰撞」,因此推荐在 session_start() 之后调用再 session_id($new) 换 ID(配合 session_regenerate_id 的自定义流程,手册示例即此模式);前缀只允许 [a-zA-Z0-9,-](部分存储按 ID 前缀分桶);且不要用机密信息当前缀。ID 长度/字符集由 session.sid_length/session.sid_bits_per_character 决定(PHP 8.4 起这两项 ini 已弃用,ID 固定 32 位十六进制)。
Python:secrets.token_hex(16) 直接对齐 PHP 默认形态;secrets 模块是官方指定的「安全随机」入口(random 模块不安全)。
Rust:std 无 CSPRNG——uuid crate(Uuid::new_v4())或 rand crate 是标配;示例的时间派生 ID 仅演示格式。
TypeScript:同 JavaScript。