Cannot start session for framework-x built-in web server
mrpachara opened this issue · 2 comments
I try to add a simple middleware for start session as the following code. I get a waring:
PHP Warning: session_start(): Session cannot be started after headers have already been sent
when I use framework-x built-in web server:
php public/index.php
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
$app = new FrameworkX\App();
$app->get(
'/',
function (
Psr\Http\Message\ServerRequestInterface $request,
callable $next,
) {
\session_start();
return $next($request);
},
function () {
$_SESSION['my-test'] = 'My Test';
return React\Http\Message\Response::plaintext('My Test');
},
);
$app->run();
But this does not happen when I use PHP build-in web server:
php -S localhost:8080 public/index.php
Version:
clue/framework-x v0.16.0
Now I know that framework-x build-in server runs in CLI mode. That uses a single process to handle all requests. So, all of build-in PHP functions session_*
cannot work with it. In this case, we have to create the session manually and assign a cookie directly to Response
object or find some session libraries that can work with CLI mode.
So, I close this issue due to it is not a bug.
@mrpachara Thanks for bringing this up 👍
Now I know that framework-x build-in server runs in CLI mode. That uses a single process to handle all requests. So, all of build-in PHP functions session_* cannot work with it
The PHP sessions require global state and are mostly designed for shared nothing architecture, so this makes it a bad fit for a middleware-based approach, especially with the built-in web server handling multiple requests. You can still use them if they're carefully configured, but this obviously depends on your use case here.
You could also look for other solutions that don't rely on PHP built-in sessions and just build on top of the basic concept of sessions instead.