Laravel 发送响应

本文介绍了Laravel框架中响应发送的具体实现方式,包括响应头、响应体的发送过程及fastcgi模式下的处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Laravel 发送响应

public function send()
{
    $this->sendHeaders();
    $this->sendContent();

    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    } elseif ('cli' !== PHP_SAPI) {
        static::closeOutputBuffers(0, true);
    }

    return $this;
}

发送响应头

public function sendHeaders()
{
    if (headers_sent()) {
        return $this;
    }

    if (!$this->headers->has('Date')) {
        $this->setDate(\DateTime::createFromFormat('U', time()));
    }

    foreach ($this->headers->allPreserveCase() as $name => $values) {
        foreach ($values as $value) {
            header($name.': '.$value, false, $this->statusCode);
        }
    }

    header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);

    foreach ($this->headers->getCookies() as $cookie) {
        if ($cookie->isRaw()) {
            setrawcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
        } else {
            setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
        }
    }

    return $this;
}

发送响应体

public function sendContent()
{
    echo $this->content;

    return $this;
}

发送到客户端

// 若是 fastcgi 模式,则结束客户端响应后异步执行服务器端的后续任务,例如中间件的 terminate 方法和事件等
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
} elseif ('cli' !== PHP_SAPI) {
    static::closeOutputBuffers(0, true);
}
public static function closeOutputBuffers($targetLevel, $flush)
{
    $status = ob_get_status(true);
    $level = count($status);
    $flags = defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE) : -1;

    while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || $flags === ($s['flags'] & $flags) : $s['del'])) {
        if ($flush) {
            ob_end_flush();
        } else {
            ob_end_clean();
        }
    }
}

后续动作

执行中间件的 terminate 方法和事件等

至此,框架核心流程全部走完

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值