Any ideas why setting headers like this doesn't work:
Code:
$this->response->setContentType('text/event-stream')
but using like this works?
Code:
header('Content-Type: text/event-stream')
I've build the following MWE running on a fresh install of CI4's appstarter:
PHP Code:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class Headers extends Controller
{
public function not_working(): void
{
$this->response->setContentType('text/event-stream');
$this->response->setHeader('Content-Type', 'text/event-stream')
->setHeader('Cache-Control', 'no-cache')
->setHeader('Connection', 'keep-alive')
->setHeader('Access-Control-Allow-Origin', '*');
// data to be sent
$data = [
'timestamp' => time()
];
// Send the SSE data to the client
echo "data: " . json_encode($data) . "\n\n";
@flush();
}
public function working(): void
{
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('Access-Control-Allow-Origin: *');
// data to be sent
$data = [
'timestamp' => time()
];
// Send the SSE data to the client
echo "data: " . json_encode($data) . "\n\n";
@flush();
}
}
Routes are configured like this:
PHP Code:
<?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
$routes->get('/', 'Home::index');
$routes->get('/working', 'Headers::working');
$routes->get('/not-working', 'Headers::not_working');
You will notice that the response header of "/not-working" is "text/html; charset=UTF-8" instead of "text/stream-event", tested with Apache/2.4.56 (Win 11 and Debian 12) with or without nginx reverse proxy.
To my surprise, with LiteSpeed or OpenLiteSpeed server "/not-working" returns the correct headers

Any ideas why both "$this->response->setContentType('text/event-stream');" and "$this->response->setHeader('Content-Type', 'text/event-stream')?" does not in my controller?
TIA.