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
5 changes: 5 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ PHP NEWS
registrations are freed while still reachable from the cycle collector.
(Ilia Alshanetsky)

- Session:
. Fixed session data loss in the files save handler when writing the session
file fails after it was already truncated. (Ilia Alshanetsky)



24 Sep 2026, PHP 8.4.26

Expand Down
9 changes: 4 additions & 5 deletions ext/session/mod_files.c
Original file line number Diff line number Diff line change
Expand Up @@ -236,11 +236,6 @@ static zend_result ps_files_write(ps_files *data, zend_string *key, zend_string
return FAILURE;
}

/* Truncate file if the amount of new data is smaller than the existing data set. */
if (ZSTR_LEN(val) < data->st_size) {
php_ignore_value(ftruncate(data->fd, 0));
}

#ifdef HAVE_PWRITE
n = pwrite(data->fd, ZSTR_VAL(val), ZSTR_LEN(val), 0);
#else
Expand Down Expand Up @@ -274,6 +269,10 @@ static zend_result ps_files_write(ps_files *data, zend_string *key, zend_string
return FAILURE;
}

if (ZSTR_LEN(val) < data->st_size) {
php_ignore_value(ftruncate(data->fd, ZSTR_LEN(val)));
}

return SUCCESS;
}

Expand Down
60 changes: 60 additions & 0 deletions ext/session/tests/session_write_failure_keeps_data.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
--TEST--
Session files handler must not truncate session file when write fails
--EXTENSIONS--
session
posix
pcntl
--INI--
error_reporting=E_ALL
display_errors=1
session.use_strict_mode=0
--FILE--
<?php
$dir = sys_get_temp_dir() . '/aph_er5_' . getmypid();
if (!is_dir($dir)) {
mkdir($dir);
}
foreach (glob($dir . '/sess_*') as $f) {
unlink($f);
}
ini_set('session.save_path', $dir);

$sid = 'apher5sessid12345678901234567890';
$file = $dir . '/sess_' . $sid;

ob_start();

session_id($sid);
session_start();
$_SESSION['data'] = str_repeat('A', 8192);
session_write_close();

clearstatcache(true);
$before = filesize($file);
var_dump($before > 4096);

pcntl_signal(SIGXFSZ, SIG_IGN);
var_dump(posix_setrlimit(POSIX_RLIMIT_FSIZE, 16, POSIX_RLIMIT_INFINITY));

session_start();
$_SESSION['data'] = str_repeat('B', 4096);
@session_write_close();

clearstatcache(true);
$after = filesize($file);
var_dump($after);
var_dump($after === $before);

ob_end_flush();

foreach (glob($dir . '/sess_*') as $f) {
@unlink($f);
}
@rmdir($dir);
Comment on lines +50 to +53

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Add --CLEAN-- and remove the defensive cleanup at the beginning?

echo "done\n";
--EXPECT--
bool(true)
bool(true)
int(8207)
bool(true)
done
Loading