Skip to content

Running out of memory in custom session handler's write function causes "Cannot call session save handler in a recursive manner" #15529

Open
@ssigwart

Description

@ssigwart

Description

The following code:

<?php

ini_set('memory_limit', '16M');

class TestSessionHandler implements SessionHandlerInterface
{
	public function close(): bool
	{
		error_log("Close");
		return true;
	}
	public function destroy(string $id): bool
	{
		error_log("Destroy");
		return true;
	}
	public function gc(int $max_lifetime): int|false
	{
		error_log("GC");
		return 0;
	}
	public function open(string $path, string $name): bool
	{
		error_log("Open");
		return true;
	}
	public function read(string $id): string|false
	{
		error_log("Read");
		return 'a|i:1234;';
	}
	public function write($id, $data): bool
	{
		error_log("About to run out of memory");
		var_dump(strlen(str_repeat('0', 16777216)));
		error_log("Wrote session");
		return true;
	}
}

session_set_save_handler(new TestSessionHandler());
session_start();
error_log("End of code");

Resulted in this output:

Open
Read
End of code
About to run out of memory
PHP Fatal error:  Allowed memory size of 16777216 bytes exhausted (tried to allocate 16777248 bytes) in /Users/ssigwart/Downloads/sessionsTest.php on line 35

Fatal error: Allowed memory size of 16777216 bytes exhausted (tried to allocate 16777248 bytes) in /Users/ssigwart/Downloads/sessionsTest.php on line 35
PHP Warning:  PHP Request Shutdown: Cannot call session save handler in a recursive manner in Unknown on line 0

Warning: PHP Request Shutdown: Cannot call session save handler in a recursive manner in Unknown on line 0
PHP Warning:  PHP Request Shutdown: Failed to write session data using user defined save handler. (session.save_path: /usr/local/share/phpsess, handler: TestSessionHandler::updateTimestamp) in Unknown on line 0

Warning: PHP Request Shutdown: Failed to write session data using user defined save handler. (session.save_path: /usr/local/share/phpsess, handler: TestSessionHandler::updateTimestamp) in Unknown on line 0
Close

But I expected this output instead:

Open
Read
End of code
About to run out of memory
PHP Fatal error:  Allowed memory size of 16777216 bytes exhausted (tried to allocate 16777248 bytes) in /Users/ssigwart/Downloads/sessionsTest.php on line 35

I'd expect the fatal error, but not the recursive session call.

The above simulates the error using a large string, but this happens when a session is large and the custom error handler needs to allocate some more data to write the data.

PHP Version

PHP 8.1.29, PHP 8.3.10

Operating System

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions