session_gc
session_gc(): int|false
Runs one round of session garbage collection immediately (removing expired session data) and returns the number of deleted entries; a replacement for probabilistic gc_probability triggering, invoked from cron on busy sites.
C C23
#include <stdio.h>
/* records with a last-activity timestamp; gc drops those older than TTL */
struct Rec {
char sid[16];
long lastActive;
};
int main(void) {
long now = 1000000000L;
struct Rec store[3] = {
{"sess-old1", now - 7200}, /* expired: 2h idle, TTL 1h */
{"sess-new1", now - 600}, /* alive: 10 min idle */
{"sess-old2", now - 4000}, /* expired */
};
int n = 3, ttl = 3600, removed = 0;
int keep = 0;
for (int i = 0; i < n; i++) {
if (now - store[i].lastActive > ttl) {
removed++; /* session_gc(): collect it */
} else {
store[keep++] = store[i];
}
}
printf("expired removed: %d\n", removed);
printf("kept: %d\n", keep);
return 0;
}
expired removed: 2 kept: 1
C++ C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Rec { std::string sid; long lastActive; };
int main() {
// storage sweep with a TTL — the language-level shape of session_gc
const long now = 1000000000L, ttl = 3600;
std::vector<Rec> store = {
{"sess-old1", now - 7200}, // expired: 2h idle
{"sess-new1", now - 600}, // alive: 10 min idle
{"sess-old2", now - 4000}, // expired
};
const auto it = std::stable_partition(store.begin(), store.end(),
[&](const Rec& r) { return now - r.lastActive <= ttl; });
const int removed = static_cast<int>(store.end() - it);
store.erase(it, store.end());
std::cout << "expired removed: " << removed << "\n";
std::cout << "kept: " << store.size() << "\n";
return 0;
}
expired removed: 2 kept: 1
C# v11.0.100
// TTL sweep over a session store — the language-level shape of session_gc
var store = new List<(string Sid, long LastActive)>
{
("sess-old1", 999992800), // expired: 2h idle
("sess-new1", 999999400), // alive: 10 min idle
("sess-old2", 999996000), // expired
};
long now = 1000000000L, ttl = 3600;
int removed = store.RemoveAll(r => now - r.LastActive > ttl);
Console.WriteLine("expired removed: " + removed);
Console.WriteLine("kept: " + store.Count);
expired removed: 2 kept: 1
Go v1.27.4
package main
import "fmt"
type rec struct {
sid string
lastActive int64 // seconds
}
func main() {
// TTL sweep over a session store — the language-level shape of session_gc
now, ttl := int64(1000000000), int64(3600)
store := []rec{
{"sess-old1", now - 7200}, // expired: 2h idle
{"sess-new1", now - 600}, // alive: 10 min idle
{"sess-old2", now - 4000}, // expired
}
kept := store[:0]
removed := 0
for _, r := range store {
if now-r.lastActive > ttl {
removed++
} else {
kept = append(kept, r)
}
}
fmt.Println("expired removed:", removed)
fmt.Println("kept:", len(kept))
}
expired removed: 2 kept: 1
Java v27.0.1
import java.util.ArrayList;
import java.util.List;
public class Main {
record Rec(String sid, long lastActive) {}
public static void main(String[] args) {
// TTL sweep over a session store — the language-level shape of session_gc
long now = 1_000_000_000L, ttl = 3600;
List<Rec> store = new ArrayList<>(List.of(
new Rec("sess-old1", now - 7200), // expired: 2h idle
new Rec("sess-new1", now - 600), // alive: 10 min idle
new Rec("sess-old2", now - 4000) // expired
));
int removed = 0;
for (int i = store.size() - 1; i >= 0; i--) {
if (now - store.get(i).lastActive() > ttl) { store.remove(i); removed++; }
}
System.out.println("expired removed: " + removed);
System.out.println("kept: " + store.size());
}
}
expired removed: 2 kept: 1
JavaScript v26.13.1
// TTL sweep over a session store — the language-level shape of session_gc;
// real stores own their expiry (Redis EXPIRE, connect-redis TTL options)
const store = [
{ sid: "sess-old1", lastActive: 999992800000 }, // expired: 2h idle
{ sid: "sess-new1", lastActive: 999999400000 }, // alive: 10 min idle
{ sid: "sess-old2", lastActive: 999996000000 }, // expired
];
const now = 1000000000000, ttl = 3600_000;
const kept = store.filter(r => now - r.lastActive <= ttl);
const removed = store.length - kept.length;
console.log("expired removed:", removed);
console.log("kept:", kept.length);
expired removed: 2 kept: 1
PHP v8.6.0
// session_gc: triggers collection immediately instead of the probabilistic
// gc_probability roll. Returns the number of deleted session entries (int, or false on failure).
ini_set("session.save_path", sys_get_temp_dir());
session_start();
$n1 = session_gc(); // CLI works too, provided save_path matches the web requests
session_destroy();
// Isolated dir demo: age one stored session past gc_maxlifetime, then collect exactly it.
$tmp = sys_get_temp_dir() . "/codeabc-a45-gc";
if (!is_dir($tmp)) { mkdir($tmp, 0700, true); }
ini_set("session.save_path", $tmp);
session_start();
$_SESSION["x"] = 1;
session_write_close();
$files = glob($tmp . "/sess_*");
touch($files[0], time() - 7200); // pretend 2h passed (sets mtime+atime)
ini_set("session.gc_maxlifetime", "3600"); // 1h lifetime -> the aged file is now expired
session_start();
$n2 = session_gc();
session_destroy();
foreach (glob($tmp . "/sess_*") as $f) { unlink($f); }
rmdir($tmp);
echo "gc returns int: ", var_export(is_int($n1), true), "\n";
echo "gc >= 0: ", var_export($n1 >= 0, true), "\n";
echo "aged file collected: ", var_export($n2 === 1, true);
gc returns int: true gc >= 0: true aged file collected: true
Python v3.15.2
# TTL sweep over a session store — the language-level shape of session_gc;
# real stores own their expiry (Redis EXPIRE, Django's session cleanup command)
store = {
"sess-old1": 999992800, # expired: 2h idle
"sess-new1": 999999400, # alive: 10 min idle
"sess-old2": 999996000, # expired
}
now, ttl = 1000000000, 3600
expired = [sid for sid, ts in store.items() if now - ts > ttl]
for sid in expired:
del store[sid]
print("expired removed:", len(expired))
print("kept:", len(store))
expired removed: 2 kept: 1
Rust v1.99.1
fn main() {
// TTL sweep over a session store — the language-level shape of session_gc;
// real stores own their expiry (Redis EXPIRE, session crates' expiry columns)
let now: i64 = 1_000_000_000;
let ttl: i64 = 3600;
let mut store: Vec<(String, i64)> = vec![
("sess-old1".into(), now - 7200), // expired: 2h idle
("sess-new1".into(), now - 600), // alive: 10 min idle
("sess-old2".into(), now - 4000), // expired
];
let before = store.len();
store.retain(|(_, ts)| now - ts <= ttl);
println!("expired removed: {}", before - store.len());
println!("kept: {}", store.len());
}
expired removed: 2 kept: 1
TypeScript v26.13.1
// TTL sweep over a session store — the language-level shape of session_gc;
// real stores own their expiry (Redis EXPIRE, connect-redis TTL options)
interface Rec { sid: string; lastActive: number; }
const store: Rec[] = [
{ sid: "sess-old1", lastActive: 999992800000 }, // expired: 2h idle
{ sid: "sess-new1", lastActive: 999999400000 }, // alive: 10 min idle
{ sid: "sess-old2", lastActive: 999996000000 }, // expired
];
const now = 1000000000000, ttl = 3600_000;
const kept: Rec[] = store.filter(r => now - r.lastActive <= ttl);
const removed: number = store.length - kept.length;
console.log("expired removed:", removed);
console.log("kept:", kept.length);
expired removed: 2 kept: 1
Language differences
C: no session concept — expiry handling means self-managed timers/timestamp filtering (the TTL sweep here); file stores can mirror the PHP files handler by judging expiry from mtime.
C++: same as C; vector::erase/stable_partition sweeps the store, and real systems run it from a background thread on a schedule.
C#: at the language level only TTL filtering; ASP.NET expires session state automatically (SessionStateModule, Session.Timeout) — no manual GC; distributed stores lean on Redis EXPIRE.
Go: at the language level only a TTL sweep; gorilla/sessions file/cookie stores do not actively collect — production uses Redis TTL or a hand-written cron.
Java: Servlet containers (Tomcat etc.) expire sessions themselves (session-config timeout in web.xml); Redis setups lean on EXPIRE — no manual GC needed.
JavaScript: at the language level a TTL sweep; express-session stores (connect-redis etc.) delegate expiry to Redis/Mongo TTL mechanisms.
PHP: by default GC fires probabilistically per request via session.gc_probability/gc_divisor — low-traffic sites may never collect while busy ones collect too often, so production sets the probability to 0 and calls session_gc() from cron; the return value is the number of deleted entries (legacy handlers always return 1); from CLI the save_path must match the web requests and need delete permission (container PrivateTmp isolates /tmp). session.gc_maxlifetime controls the lifetime, default 1440 seconds.
Python: at the language level TTL filtering; Django cleans DB backends with the clearsessions management command, Redis backends use EXPIRE; Flask signed-cookie sessions keep no server-side store, hence no GC.
Rust: at the language level Vec::retain keeps survivors; axum-session's storage layer (Redis/SQLx) configures expiry separately.
TypeScript: same as JavaScript.