以下是 PHP 中跨文件传递参数的 8 种常见方法,按场景和安全性分类整理,附详细说明和示例代码:
1 2 3 4 5 |
// file1.php <a href="file2.php?id=123&name=John">跳转</a> // file2.php $id = $_GET['id']; // 获取 123 $name = $_GET['name']; // 获取 John |
1 2 3 4 5 6 |
// file1.php session_start(); $_SESSION['user'] = 'Alice'; // file2.php session_start(); echo $_SESSION['user']; // 输出 Alice |
1 2 3 4 |
// file1.php setcookie("theme", "dark", time() + 86400); // file2.php echo $_COOKIE['theme']; // 输出 dark |
1 2 3 4 5 |
// config.php $db_host = 'localhost'; // file1.php include 'config.php'; echo $db_host; // 输出 localhost |
1 2 3 4 |
// file1.php file_put_contents('data.txt', 'Hello World'); // file2.php $data = file_get_contents('data.txt'); // 读取 Hello World |
1 2 3 4 5 6 |
// file1.php $pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'); $pdo->exec("INSERT INTO messages (content) VALUES ('Hello')"); // file2.php $stmt = $pdo->query("SELECT content FROM messages"); $data = $stmt->fetchAll(); |
1 2 3 4 5 6 |
// file1.php $data = ['name' => 'Bob', 'age' => 30]; file_put_contents('data.dat', serialize($data)); // file2.php $data = unserialize(file_get_contents('data.dat')); echo $data['name']; // 输出 Bob |
1 2 3 4 5 6 7 8 |
// Config.php class Config { public static $value = 'default'; } // file1.php Config::$value = 'new value'; // file2.php echo Config::$value; // 输出 new value |
方法 | 适用场景 | 安全性 | 持久性 | 数据量限制 |
---|---|---|---|---|
$_GET/$_POST | 表单/URL 传参 | 低 | 无 | 小 |
$_SESSION | 用户会话数据 | 高 | 会话级 | 中等 |
$_COOKIE | 客户端存储配置 | 中 | 长期 | 小 |
文件包含 | 同请求共享配置 | 中 | 无 | 大 |
文件存储 | 持久化非敏感数据 | 低 | 长期 | 大 |
数据库 | 结构化数据共享 | 高 | 长期 | 大 |
序列化 | 复杂数据结构 | 低 | 长期 | 大 |
静态类属性 | 全局配置/状态管理 | 中 | 请求级 | 大 |