You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止Symfony读取请求体,以流方式处理HTTP请求内容?

Symfony 6中流式处理大请求体的解决方案

在Symfony控制器中直接读取php://input处理大请求体时,会触发内存耗尽错误,原因是HttpFoundation组件默认会预加载整个请求体到内存中(内部调用了Request::getContent())。以下是两种解决办法:

方法一:使用Request对象的流式API替代php://input

Symfony的Request类提供了getStream()方法,返回一个流式处理的StreamInterface实例,无需一次性加载所有内容到内存:

#[Route('/my-endpoint', name: 'my.endpoint', methods: 'PUT')]
public function action(Request $request): Response
{
    $bodyStream = $request->getStream();
    $bufLength = 10000;
    
    while (!$bodyStream->eof()) {
        $buf = $bodyStream->read($bufLength);
        // 处理缓冲区数据
    }

    return new Response("hello");
}

方法二:禁用路由的自动内容解析

如果需要继续使用php://input,可以为目标路由添加disable_content_parsing选项,阻止Symfony预读和解析请求体:

注解路由配置

#[Route(
    '/my-endpoint', 
    name: 'my.endpoint', 
    methods: 'PUT',
    options: ['disable_content_parsing' => true]
)]
public function action(): Response
{
    $bodyStream = fopen('php://input', 'r');
    $bufLength = 10000;
    
    while($buf = stream_get_contents($bodyStream, $bufLength)) {
        // 处理缓冲区数据
    }

    return new Response("hello");
}

YAML路由配置(若使用YAML)

my.endpoint:
    path: /my-endpoint
    methods: [PUT]
    controller: App\Controller\YourController::action
    options:
        disable_content_parsing: true

注意:启用disable_content_parsing后,$request->request、$request->getContent()等依赖请求体解析的功能将无法使用,需根据业务场景选择。

内容的提问来源于stack exchange,提问作者sgt-hartman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 02:13:22