Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions system/CodeIgniter.php
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,8 @@ public function run(?RouteCollectionInterface $routes = null, bool $returnRespon

$this->sendResponse();

Events::trigger('post_response');

return null;
}

Expand Down
25 changes: 25 additions & 0 deletions system/HTTP/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -385,9 +385,34 @@ public function send()
$this->sendCookies();
$this->sendBody();

$this->finishResponse();

return $this;
}

private function finishResponse(): void
{
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
} elseif (function_exists('litespeed_finish_request')) {
litespeed_finish_request();
} elseif (! in_array(PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
$this->closeOutputBuffers();
flush();
}
}

private function closeOutputBuffers(): void
{
$status = ob_get_status(true);
$level = count($status);
$flags = PHP_OUTPUT_HANDLER_REMOVABLE | PHP_OUTPUT_HANDLER_FLUSHABLE;

while ($level-- > 0 && ($s = $status[$level]) && ($s['del'] ?? (! isset($s['flags']) || ($s['flags'] & $flags) === $flags))) {

@paulbalandan paulbalandan Jul 22, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you destructure/rewrite this whole conditional line to be more readable?

ob_end_flush();
}
}

/**
* Decides whether {@see ContentSecurityPolicy::finalize()} should run for
* this response. Keeping the CSP class unloaded on requests that do not
Expand Down
35 changes: 35 additions & 0 deletions tests/_support/HTTP/Responses/ResponseWithPostSendFlag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\HTTP\Responses;

use CodeIgniter\HTTP\Response;

class ResponseWithPostSendFlag extends Response
{
public $responseSent = false;

/**
* Sends the output to the browser.
*
* @return $this
*/
public function send()
{
parent::send();

$this->responseSent = true;

return $this;
}
}
22 changes: 22 additions & 0 deletions tests/system/CodeIgniterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use CodeIgniter\Config\Factories;
use CodeIgniter\Config\Services;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\Method;
use CodeIgniter\HTTP\Response;
Expand All @@ -38,6 +39,7 @@
use PHPUnit\Framework\Attributes\WithoutErrorHandler;
use Tests\Support\Filters\Customfilter;
use Tests\Support\Filters\RedirectFilter;
use Tests\Support\HTTP\Responses\ResponseWithPostSendFlag;
use Tests\Support\Router\Filters\TestAttributeFilter;

/**
Expand Down Expand Up @@ -1328,4 +1330,24 @@ public function testResetForWorkerModeDoesNotLoadCspWhenDisabled(): void
$this->assertNull(RichRenderer::$css_nonce);
$this->assertTrue(RichRenderer::$needs_pre_render);
}

public function testPostResponseTriggeredAfterSend(): void
{
$this->resetServices();

$response = new ResponseWithPostSendFlag();
Services::injectMock('response', $response);

$postResponseTriggeredAfterResponseSent = false;

Events::on('post_response', static function () use (&$postResponseTriggeredAfterResponseSent, &$response): void {
$postResponseTriggeredAfterResponseSent = $response->responseSent;
});

ob_start();
$this->codeigniter->run();
ob_get_clean();

$this->assertTrue($postResponseTriggeredAfterResponseSent);
}
}
1 change: 1 addition & 0 deletions user_guide_src/source/changelogs/v4.8.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ Others
- **Filters:** Added ``RequestId`` filter for request tracing and correlation logging. The filter stores the request ID in the request context and automatically adds the ``X-Request-ID`` response header. Incoming ``X-Request-ID`` headers are used when valid. See :ref:`requestid` for details.
- **Environment:** Added ``CodeIgniter\EnvironmentDetector`` class and corresponding ``environment`` service as a mockable wrapper around the ``ENVIRONMENT`` constant.
Framework internals that previously compared ``ENVIRONMENT`` directly now go through this service, making environment-specific branches reachable in tests via ``Services::injectMock()``. See :ref:`environment-detector-service`.
- **Events**: Added ``post_response`` event to run after the response is sent to the client.
- **Time:** Added ``Time::between()``, ``Time::min()``, and ``Time::max()`` comparison helpers. See :ref:`between <time-comparing-two-times-between>`, :ref:`min <time-comparing-two-times-min>`, and :ref:`max <time-comparing-two-times-max>`.

***************
Expand Down
4 changes: 4 additions & 0 deletions user_guide_src/source/extending/events.rst
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ invoked by **public/index.php**:
* **post_controller_constructor** Called immediately after your controller is instantiated, but prior to any method calls happening.
* **post_system** Called right before the final rendered page is sent to the browser,
at the end of system execution, after the execution of "after" controller filters.
* **post_response** Called after the response is sent to the client. This event is useful
for performing tasks that do not need to be completed before the response is sent, such as logging or cleanup tasks.

.. note:: The ``post_response`` event was added in v4.8.0.

.. _event-points-for-cli-apps:

Expand Down
Loading