Coder Social home page Coder Social logo

swoole-session's Introduction

PHP Sessions for Swoole Build Status

This library implements compatibility of native PHP sessions with Swoole / Open Swoole web-server.

Features:

  • Transparent session start/stop
  • Session ID in cookies or query string
  • Native or custom session ID generator
  • Automatic session data persistence
  • Compliance with PHP session configuration

Installation

The library is to be installed via Composer as a dependency:

composer require upscale/swoole-session

Usage

Wrap your request handling middleware into the session decorator:

require 'vendor/autoload.php';

use Upscale\Swoole\Session\SessionDecorator;

$server = new \Swoole\Http\Server('127.0.0.1', 8080);
$server->set([
    // Disable coroutines to safely access $_SESSION
    'enable_coroutine' => false,
]);
$server->on('request', new SessionDecorator(function ($request, $response) {
    $_SESSION['data'] ??= rand();
    $response->end($_SESSION['data']);
}));

$server->start();

Limitations

Coroutines

PHP sessions rely on the superglobal variable $_SESSION making them incompatible with the Swoole coroutines. When a request idles for an asynchronous I/O operation, its worker process is reused to handle other request(s). Swoole switches the call stack context, but the superglobals stay in memory shared across coroutines/requests. Session data loaded for one request leaks to other requests causing all sorts of data integrity issues.

Disable coroutines to safely use the PHP sessions:

$server->set([
    'enable_coroutine' => false,
]);

Output

Direct output bypassing the response instance \Swoole\Http\Response is prohibited in the Swoole environment. Writing to the standard output stream violates the headers_sent requirement of the PHP session functions:

PHP Warning: session_start(): Cannot start session when headers already sent

Statements that "send headers" and hinder the sessions:

  • echo/print
  • fwrite(STDOUT)
  • file_put_contents('php://stdout')
  • include 'template.phtml'
  • header()
  • setcookie/setrawcookie()
  • etc.

Output buffering commonly used by template engines avoids this pitfall, for example:

ob_start();
include $templatePhtml;
$output = ob_get_clean();

$response->end($output);

Warning! Coroutines used to "send headers" despite the output buffering until this has been fixed in Swoole 4.5.3. This is not a problem since coroutines have to be disabled for the data integrity reasons discussed above.

Blocking

Concurrent requests are prone to the session write race conditions. The default file-based session storage of PHP employs the filesystem locking to avoid the data corruption. Requests of the same session ID execute sequentially blocking their respective worker processes from session_start() until session_write_close().

Asynchronous coroutine-aware libraries built specifically for Swoole:

License

Licensed under the Apache License, Version 2.0.

swoole-session's People

Contributors

sshymko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

swoole-session's Issues

Success file of session, then fail redis of session.

Dear friends.

Session management with files was successful in the swoole environment,
but session information cannot be generated on the redis server when managing sessions with redis.

<< test result >>

nginx + php-fpm = redis session test success

nginx + php-fpm = file session test success

swoole + SessionMiddleware = file session test succes (session.save_handler=file)

swoole + SessionMiddleware = redis session test fail (session.save_handler=redis)

<< php.ini - fail config >>

session.save_handler=redis

session.save_path="tcp://localhost:6379?auth=1234"

php : 7.4.15

swoole : 4.6.5

[INFO] session and headers already sent

When starting a website conversion with swoole, I had to use this middleware to be able to use the sessions properly.
Like many people using twig for rendering, I ran into the typical header already sent problem when working with sessions.

While trying to understand the origin with the #1 issue and searching on the internet, I could observe that nobody else had looked at the issue.

So, through this issue I would like to bring for future people, how I could solve my problem and why. Any information is good to take from other people.

I can already say that I have had no problems with coroutine so far.

So to start with, I made a simple application like everyone else, with these few lines:

$server = new Swoole\HTTP\Server("localhost", 9501);

$server->on("WorkerStart", function($server, $workerId) {
    echo "Worker Start: $workerId\n";
});

$server->on("Start", function() {
	echo "Swoole HTTP Server Started @ 127.0.0.1:9501\n";
});

$server->on('Request', new SessionMiddleware(function (Swoole\Http\Request $request,Swoole\Http\Response $response) use ($app) {
    $response->end("Hello world !");
}));

$server->on("Shutdown", function($server, $workerId) {
	echo "Server shutting down...\n";
});

// Triggered when worker processes are being stopped
$server->on("WorkerStop", function($server, $workerId) {
	echo "Worker Stopped: $workerId\n";
});

$server->start();

A basic web server with swoole using SessionMiddleware.

However, warnings will appear every time you want to access your site. Normal, we'll see about that.
I thought it was a problem on the on('Request') side, but not at all because we finish the request directly, so there is no need to print elsewhere.

After some research, I noticed that by removing the echo from WorkerStart, everything worked fine. And this is quite logical, in fact, since they are the ones who will carry out the different requests, if we do an echo, the requests that we will process afterwards will be bugged as we do not want.

In conclusion, when rendering with any library, as a precaution use the output buffering to prevent any risk.
As for logging, rather than echoing or printing, use a lib to log like monolog under file to avoid any risk of writing to the buffer.

And if we follow these precautions, I do not see why coroutine would not work, if nothing is written in the buffer.
However, as soon as a PHP warning is thrown by the code and this one is displayed, the system will bug. It is therefore necessary to prevent any risk by removing warnings?

Not working with Twig template engine.

Hi,
Should swoole-session be working with Swoole 4.5.2, PHP 7.4.3?

This is what I'm getting:

PHP Warning:  session_id(): Cannot change session id when headers already sent in /var/www/html/mvc_swoole/vendor/upscale/swoole-session/src/SessionMiddleware.php on line 62
PHP Warning:  session_start(): Cannot start session when headers already sent in /var/www/html/mvc_swoole/vendor/upscale/swoole-session/src/SessionMiddleware.php on line 63
PHP Warning:  session_id(): Cannot change session id when headers already sent in /var/www/html/mvc_swoole/vendor/upscale/swoole-session/src/SessionMiddleware.php on line 80

Regards.

Compatibility with openswoole

Could this be compatible with openswoole? atm composer complains about the missing extension when using openswoole.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.