session_create_id

session_create_id(string $prefix = ""): string|false

Creates a collision-free session ID (charset [0-9a-zA-Z,-], optional prefix); the ID shape (length/charset) follows php.ini. Performs a collision check while a session is active — the companion tool for user-level save handlers.

C C23

C23
#include <stdio.h>
#include <string.h>
#include <time.h>

/* no CSPRNG in the C standard library: a real handler would use getrandom/arc4random;
   a time+counter-derived hex id shows the FORMAT contract (32 hex chars, optional prefix) */
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;
}
Output
format ok: true
prefix ok: true
length ok: true
distinct: true

C++ C++26

C++26
#include <chrono>
#include <iostream>
#include <cstdio>
#include <string>

static std::string hexId() {
    /* std has no CSPRNG: real code reaches for a crypto RNG; a time-derived
       hex id demonstrates the format contract (32 hex chars) */
    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;
}
Output
format ok: true
prefix ok: true
length ok: true
distinct: true

C# v11.0.100

v11.0.100
// Guid.NewGuid() is the .NET counterpart of PHP's collision-free ID generator
string id = System.Guid.NewGuid().ToString("N");   // 32 hex chars, no dashes
string prefixed = "user-" + id;                     // prefix like 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")));
Output
format ok: True
prefix ok: True
length ok: True
distinct: True

Go v1.27.4

v1.27.4
package main

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"strings"
)

func newId(prefix string) string {
	// crypto/rand is the CSPRNG counterpart of PHP's session ID generator
	b := make([]byte, 16)
	rand.Read(b) // 16 bytes -> 32 hex chars, the default PHP id shape
	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)
}
Output
format ok: true
prefix ok: true
length ok: true
distinct: true

Java v27.0.1

v27.0.1
import java.util.UUID;

public class Main {
    public static void main(String[] args) {
        // UUID.randomUUID() is the CSPRNG-backed counterpart of PHP's id generator
        String id = UUID.randomUUID().toString();          // 36 chars with dashes
        String prefixed = "user-" + id;                    // prefix like 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()));
    }
}
Output
format ok: true
prefix ok: true
length ok: true
distinct: true

JavaScript v26.13.1

v26.13.1
const { randomUUID } = require("node:crypto");

// randomUUID is the CSPRNG-backed counterpart of PHP's session id generator
const id = randomUUID();                    // 36 chars, UUID format
const prefixed = "user-" + id;              // prefix like 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());
Output
format ok: true
prefix ok: true
length ok: true
distinct: true

PHP v8.6.0

v8.6.0
// session_create_id: generates a collision-free session ID for user-level save handlers.
// ID charset and length follow php.ini; prefix allows [a-zA-Z0-9,-].
ini_set("session.save_path", sys_get_temp_dir());
$idA = session_create_id();              // no active session: collision check skipped
$idB = session_create_id("user-");       // prefixed variant
$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();              // active session: collision-checked against storage
$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);
Output
format ok: true
prefix ok: true
length ok: true
active ok: true
distinct: true

Python v3.15.2

v3.15.2
import secrets

# secrets is the CSPRNG counterpart of PHP's session id generator;
# token_hex(16) yields 32 hex chars — the default PHP id shape
id_a = secrets.token_hex(16)
id_b = "user-" + secrets.token_hex(16)   # prefix like 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-"):])
Output
format ok: True
prefix ok: True
length ok: True
distinct: True

Rust v1.99.1

v1.99.1
use std::time::{SystemTime, UNIX_EPOCH};

fn hex_id() -> String {
    /* std has no CSPRNG (real code uses the rand/uuid crates); a time-derived
       hex id demonstrates the format contract (32 hex chars) */
    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());
}
Output
format ok: true
prefix ok: true
length ok: true
distinct: true

TypeScript v26.13.1

v26.13.1
import { randomUUID } from "node:crypto";

// randomUUID is the CSPRNG-backed counterpart of PHP's session id generator
const id: string = randomUUID();           // 36 chars, UUID format
const prefixed: string = "user-" + id;     // prefix like 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());
Output
format ok: true
prefix ok: true
length ok: true
distinct: true

Language differences

C: the standard library has no CSPRNG — real code uses platform APIs (Linux getrandom, BSD/macOS arc4random_buf) or reads /dev/urandom; the time-derived value here only demonstrates the format contract and must never guard production sessions.

C++: same as C (chrono timestamp for format); real implementations use OpenSSL RAND_bytes or the system CSPRNG.

C#: Guid.NewGuid().ToString("N") is 32 hex chars, the same shape as PHP's default id (CSPRNG-backed); the "D" format is the 36-char dashed form.

Go: crypto/rand plus hex.EncodeToString over 16 bytes gives 32 hex chars, matching PHP's default id shape; remember to check rand.Read's error.

Java: UUID.randomUUID() (SecureRandom-backed) is the standard choice; its 128 bits of entropy match PHP's 32x4=128 bit default.

JavaScript: crypto.randomUUID() (Node >= 14.17 / browser Web Crypto); the difference from PHP is UUID format rather than bare hex — collision odds are equally negligible.

PHP: session_create_id's value is the collision check against storage while a session is active, so the recommended flow generates after session_start() and installs via session_id($new) (the manual's custom-regeneration recipe); prefixes accept [a-zA-Z0-9,-] (some stores shard by id prefix) and must never carry secrets. Length/charset come from session.sid_length/session.sid_bits_per_character (both ini keys are deprecated as of PHP 8.4 — ids are fixed at 32 hex chars).

Python: secrets.token_hex(16) lines up with PHP's default shape directly; the secrets module is the official secure-random entry point (the random module is not safe for this).

Rust: std has no CSPRNG — the uuid crate (Uuid::new_v4()) or rand are the defaults; the demo's time-derived id only shows the format.

TypeScript: same as JavaScript.