【发布时间】:2025-12-05 05:30:02
【问题描述】:
我正在生成一个唯一令牌并将其保存在每个请求的会话变量中(以典型的 CSRF 保护方式)。令牌在使用 POSTED 令牌值检查验证后刷新。
这是我的代码(index.php):
<?php
session_start();
if (!empty($_POST['token'])) {
var_dump($_POST['token'], $_SESSION['token']);
exit;
}
$_SESSION['token'] = rand();
echo '<form action="index.php" method="post"><input name="token" value="' . $_SESSION['token'] . '"></form>';
当我使用php -S localhost:8888 运行脚本时,它运行良好。但是当我指定像php -S localhost:8888 index.php 这样的index.php 文件时,$_SESSION['token'] 会发生变化。 ($_POST['token'] 和 $_SESSION['token'] 不匹配)。
php -S localhost:8888
php -S localhost:8888 index.php
我也尝试过使用路由文件。它也不起作用。 php -S localhost:8888 server.php
<?php
// server.php
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = urldecode($uri);
if ($uri !== '/' and file_exists($uri))
{
return false;
}
require_once 'index.php';
控制台输出:
php -S localhost:8888
php -S localhost:8878
[Mon Mar 29 11:49:49 2021] PHP 8.0.3 Development Server (http://localhost:8878) started
[Mon Mar 29 11:49:52 2021] [::1]:47410 Accepted
[Mon Mar 29 11:49:52 2021] [::1]:47412 Accepted
[Mon Mar 29 11:49:52 2021] [::1]:47410 [200]: GET /
[Mon Mar 29 11:49:52 2021] [::1]:47410 Closing
[Mon Mar 29 11:49:53 2021] [::1]:47412 [404]: GET /favicon.ico - No such file or directory
[Mon Mar 29 11:49:53 2021] [::1]:47412 Closing
php -S localhost:8888 server.php
php -S localhost:8858 server.php
[Mon Mar 29 11:48:51 2021] PHP 8.0.3 Development Server (http://localhost:8858) started
[Mon Mar 29 11:48:53 2021] [::1]:33156 Accepted
[Mon Mar 29 11:48:53 2021] [::1]:33158 Accepted
[Mon Mar 29 11:48:53 2021] [::1]:33156 Closing
[Mon Mar 29 11:48:54 2021] [::1]:33158 Closing
测试使用:
PHP 7.3.27-1~deb10u1 (cli) (built: Feb 13 2021 16:31:40) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.27, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.27-1~deb10u1, Copyright (c) 1999-2018, by Zend Technologies
和
PHP 8.0.3 (cli) (built: Mar 5 2021 08:38:30) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.3, Copyright (c) Zend Technologies
with Zend OPcache v8.0.3, Copyright (c), by Zend Technologies
这是 PHP 内置服务器的错误吗?
【问题讨论】:
-
在这种情况下为什么要将文件传递给服务器?
-
@Steven 为什么不呢?它不应该有所作为,不是吗?传递
index.php有什么缺点吗? -
@brombeer 是的,传递带有
-S的文件意味着该文件充当路由器文件,预计返回内容或false -
@Steven 但是那个脚本正在返回内容吗?
-
@brombeer 是的,确实如此,从技术上讲,我确实希望这段代码能够工作。但事实并非如此。因此,理解为什么 OP 以它们的方式做事(这会改变 PHP 的行为)似乎是一个明智的起点......作为参考,我的第二个问题是“表单是如何提交的?”
标签: php session token csrf php-builtin-server