Bertuz
Bertuz

Reputation: 2576

Is php's file_put_contents safe for concurrent reads from Nginx?

Imagine an online newspaper with static files, like the first page with the headlines. The index.html is generated by a PHP script run by cron every 5 minutes, and it writes the file on a volume shared with Nginx. The script rewrites the index.html through file_put_contents. No other process modifies the file, while Nginx returns its content.

Taking into account multiple reading accesses on the index.html per second, would file_put_contents be safe? If not: what could I use?

Upvotes: 2

Views: 107

Answers (1)

Barmar
Barmar

Reputation: 781721

No, this isn't safe. Writing to files is not atomic. If nginx tries to read the file while the script is in the middle of generating it, it will get a partial file.

Do something like this:

file_put_contents("index.html.new", $new_contents);
rename("index.html.new", "index.html");

The rename will be atomic, so nginx will get either the old or new version, but never a partial file.

Upvotes: 5

Related Questions