session_save_path
session_save_path(?string $path = null): string|false
读/写内置 files 存储的会话数据目录;设置必须在 session_start() 之前,setter 返回原路径(未设置时返回 false)。是 session_set_save_handler 之外的存储位置开关。
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void) {
/* 存储位置就是配置项:建本次运行专属目录 → 写入 → 验证 → 清理 */
const char *td = getenv("TMPDIR");
if (!td || td[0] == '\0') td = ".";
char tmpl[256];
snprintf(tmpl, sizeof tmpl, "%s/codeabc-XXXXXX", td);
char *dir = mkdtemp(tmpl);
printf("path set: %s\n", dir ? "yes" : "no");
char file[300];
snprintf(file, sizeof file, "%s/sess_demo", dir);
FILE *fp = fopen(file, "w");
fputs("k|v", fp);
fclose(fp);
printf("written: %s\n", access(file, F_OK) == 0 ? "yes" : "no");
char buf[8] = {0};
fp = fopen(file, "r");
fgets(buf, sizeof buf, fp);
fclose(fp);
printf("visible: %s\n", strcmp(buf, "k|v") == 0 ? "yes" : "no");
unlink(file);
rmdir(dir);
return 0;
}
path set: yes written: yes visible: yes
C++ C++26
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <unistd.h>
int main() {
// 存储位置就是配置项:建本次运行专属目录 → 写入 → 验证 → 清理
const char *td = std::getenv("TMPDIR");
const std::string base = (td && td[0]) ? td : ".";
char tmpl[256];
std::snprintf(tmpl, sizeof tmpl, "%s/codeabc-XXXXXX", base.c_str());
char *made = mkdtemp(tmpl);
const std::string dir = made ? made : "";
std::cout << "path set: " << (dir.empty() ? "no" : "yes") << "\n";
const std::string file = dir + "/sess_demo";
{ std::ofstream out(file); out << "k|v"; }
std::ifstream in(file);
std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
std::cout << "written: yes\n";
std::cout << "visible: " << (content == "k|v" ? "yes" : "no") << "\n";
unlink(file.c_str());
rmdir(dir.c_str());
return 0;
}
path set: yes written: yes visible: yes
C# v11.0.100
// 存储位置就是配置项:在系统临时目录下建本次运行专属子目录
string dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "codeabc-" + System.Guid.NewGuid().ToString("N")[..12]);
System.IO.Directory.CreateDirectory(dir);
Console.WriteLine("path set: yes");
string file = System.IO.Path.Combine(dir, "sess_demo");
System.IO.File.WriteAllText(file, "k|v");
Console.WriteLine("written: " + (System.IO.File.Exists(file) ? "yes" : "no"));
string back = System.IO.File.ReadAllText(file);
Console.WriteLine("visible: " + (back == "k|v" ? "yes" : "no"));
System.IO.File.Delete(file);
System.IO.Directory.Delete(dir);
path set: yes written: yes visible: yes
Go v1.27.4
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
// 存储位置就是配置项:建本次运行专属临时目录 → 写入 → 验证 → 清理
dir, err := os.MkdirTemp("", "codeabc-")
if err != nil {
panic(err)
}
fmt.Println("path set: yes")
file := filepath.Join(dir, "sess_demo")
os.WriteFile(file, []byte("k|v"), 0600)
if _, err := os.Stat(file); err == nil {
fmt.Println("written: yes")
}
data, _ := os.ReadFile(file)
fmt.Println("visible:", map[bool]string{true: "yes", false: "no"}[string(data) == "k|v"])
os.Remove(file)
os.Remove(dir)
}
path set: yes written: yes visible: yes
Java v27.0.1
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws IOException {
// 存储位置就是配置项:建本次运行专属临时目录 → 写入 → 验证 → 清理
Path dir = Files.createTempDirectory("codeabc-");
System.out.println("path set: yes");
Path file = dir.resolve("sess_demo");
Files.writeString(file, "k|v");
System.out.println("written: " + (Files.exists(file) ? "yes" : "no"));
String back = Files.readString(file);
System.out.println("visible: " + (back.equals("k|v") ? "yes" : "no"));
Files.delete(file);
Files.delete(dir);
}
}
path set: yes written: yes visible: yes
JavaScript v26.13.1
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
// 存储位置就是配置项:建本次运行专属临时目录 → 写入 → 验证 → 清理
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codeabc-"));
console.log("path set: yes");
const file = path.join(dir, "sess_demo");
fs.writeFileSync(file, "k|v");
console.log("written:", fs.existsSync(file) ? "yes" : "no");
const back = fs.readFileSync(file, "utf8");
console.log("visible:", back === "k|v" ? "yes" : "no");
fs.rmSync(dir, { recursive: true });
path set: yes written: yes visible: yes
PHP v8.6.0
// session_save_path:读/写内置 files 存储的会话数据目录
// 设置必须在 session_start() 之前;setter 返回原路径(未设置时返回 false)
$tmp = sys_get_temp_dir() . "/codeabc-a45-store";
if (!is_dir($tmp)) { mkdir($tmp, 0700, true); }
$prev = session_save_path($tmp);
$now = session_save_path();
$match = $now === $tmp;
session_start();
$_SESSION["k"] = "v";
session_write_close();
$stored = glob($tmp . "/sess_*") !== [];
session_start(); // 同一目录重新打开,证明持久化生效
$same = ($_SESSION["k"] ?? "") === "v";
session_destroy();
foreach (glob($tmp . "/sess_*") as $f) { unlink($f); }
rmdir($tmp);
echo "prev type: ", $prev === false ? "false" : "string", "\n";
echo "now matches: ", var_export($match, true), "\n";
echo "file stored: ", var_export($stored, true), "\n";
echo "reload ok: ", var_export($same, true);
prev type: string now matches: true file stored: true reload ok: true
Python v3.15.2
import os
import tempfile
# 存储位置就是配置项:建本次运行专属临时目录 → 写入 → 验证 → 清理
# (会话框架的对应物是配置里的存储路径/URL,如 Redis URL)
dir = tempfile.mkdtemp(prefix="codeabc-")
print("path set: yes")
file = os.path.join(dir, "sess_demo")
with open(file, "w") as fp:
fp.write("k|v")
print("written: yes" if os.path.exists(file) else "written: no")
with open(file) as fp:
back = fp.read()
print("visible: yes" if back == "k|v" else "visible: no")
for name in os.listdir(dir):
os.unlink(os.path.join(dir, name))
os.rmdir(dir)
path set: yes written: yes visible: yes
Rust v1.99.1
use std::fs;
use std::path::PathBuf;
fn main() {
// 存储位置就是配置项:在系统临时目录下建本次运行专属子目录
let dir: PathBuf = std::env::temp_dir().join("codeabc-save-path-demo");
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
println!("path set: yes");
let file = dir.join("sess_demo");
fs::write(&file, "k|v").unwrap();
println!("written: {}", if file.exists() { "yes" } else { "no" });
let back = fs::read_to_string(&file).unwrap();
println!("visible: {}", if back == "k|v" { "yes" } else { "no" });
fs::remove_dir_all(&dir).unwrap();
}
path set: yes written: yes visible: yes
TypeScript v26.13.1
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
// 存储位置就是配置项:建本次运行专属临时目录 → 写入 → 验证 → 清理
const dir: string = fs.mkdtempSync(path.join(os.tmpdir(), "codeabc-"));
console.log("path set: yes");
const file: string = path.join(dir, "sess_demo");
fs.writeFileSync(file, "k|v");
console.log("written:", fs.existsSync(file) ? "yes" : "no");
const back: string = fs.readFileSync(file, "utf8");
console.log("visible:", back === "k|v" ? "yes" : "no");
fs.rmSync(dir, { recursive: true });
path set: yes written: yes visible: yes
语言差异说明
C:存储位置就是自写框架的配置项(配置文件/环境变量);文件会话存储要注意每会话一文件 + 小文件密集的文件系统选型。
C++:同 C;库级可用 std::filesystem 处理路径与权限。
C#:框架层没有「存储路径」这个概念——ASP.NET 进程内状态或分布式存储(Redis 连接串);存储位置是配置项(appsettings.json)。
Go:语言级 os.MkdirTemp/os.TempDir;gorilla/sessions 的文件存储要显式传目录(FilesystemStore 的 NewFilesystemStore(path))。
Java:Servlet 容器的会话存储位置由容器配置(Tomcat 的 work 目录等);应用层 Redis 方案只有连接串。
JavaScript:语言级 os.tmpdir + mkdtemp;express-session 的 FileStore 传目录参数,生产默认换 Redis/Mongo(连接串即「路径」)。
PHP:session_save_path 只管内置 files handler(session_set_save_handler 上场后它就被自定义存储取代);必须在 session_start() 前设置;支持 N;path 形式的分层子目录(如 "2;/tmp/sessions" 按 ID 前两位散列分桶,避免单目录文件数爆炸);目录权限要给 Web 进程用户,否则 GC 删不动别人的会话文件。CLI 演示一律指向临时目录,勿脏写系统会话目录。
Python:存储位置是框架配置——Django SESSION_FILE_PATH 或 redis:// 连接;语言级 tempfile 是最接近的目录管理工具。
Rust:语言级 std::env::temp_dir;框架层存储位置在 session store 构造函数里传入(如 sqlx-sessions 的连接串)。
TypeScript:同 JavaScript。