Make WordPress Core

Opened 2 days ago

Last modified 2 days ago

#66784 new defect (bug)

WP_Filesystem_Direct::put_contents() reports success when closing the file fails

Reported by: ShaneRounce Owned by:
Priority: normal Milestone: Awaiting Review
Component: Filesystem API Version:
Severity: normal Keywords: has-patch has-unit-tests
Cc: Focuses:

Description

WP_Filesystem_Direct::put_contents() checks the byte count from fwrite() but ignores the result of fclose().

As of PHP 8.6, fclose() returns false when flushing or closing the stream fails. The method can therefore return true, and go on to change permissions, for a write that never completed.

The same PHP change was handled for image saves in [65294] (#66486) and for the test stream in [65278] (#66487).

To reproduce: on PHP 8.6, write through a stream wrapper whose stream_flush() returns false. put_contents() returns true.

Proposed fix: check the close result alongside the byte count. Patch and tests to follow in a GitHub PR.

Change History (1)

This ticket was mentioned in ​PR #16167 on ​WordPress/wordpress-develop by ​@ShaneRounce.


2 days ago
#1

  • Keywords has-patch has-unit-tests added

WP_Filesystem_Direct::put_contents() checks the byte count from fwrite() but ignores the result of fclose(). As of PHP 8.6, fclose() returns false when flushing or closing the stream fails, so the method can report success, and go on to change permissions, for a write that never completed.

This checks the close result alongside the byte count. The handle is still always closed. Successful, empty and short writes keep their existing results.

The same PHP change was handled for image saves in [65294] and for the test stream in [65278]. This covers the direct filesystem method.

Testing

Tests Assertions Result
PHP 8.6.0, trunk, putContents.php 6 10 The new flush test fails
PHP 8.6.0, this change, putContents.php 6 13 Passes
PHP 8.6.0, this change, tests/filesystem/wpFilesystemDirect 109 177 Passes
PHP 8.4.25, this change, tests/filesystem/wpFilesystemDirect 109 174 Passes, one skip (the 8.6-only test)

PHPCS passes on both changed files.

One thing to be aware of: on PHP 8.6 a userland stream wrapper with no stream_flush() method fails on close, so put_contents() would return false for it, as image saves now do.

Use of AI Tools

AI assistance: Yes
Tool(s): Codex, Claude Code
Used for: Finding the unchecked close, writing the change, the tests and this description, and running the tests. The test results above are automated runs by those tools.

Note: See TracTickets for help on using tickets.