If you're doing simple stuff like file_put_contents("index.html")
, there can be multiple problems:
- If the write fails, you're left with unwanted HTML, or empty page;
- If the server is busy, visitors can see empty page, or partial content while the PHP process is writing the file.
What you should do is use temporary files:
if (false !== file_put_contents("index.html.tmp", $data)) {
rename("index.html.tmp", "index.html");
}
Using temporary files and rename will avoid both problems described above. Works for all kinds of file types and use cases. If the rename fails, you'll still have the old version. This is good since it won't cripple your site even if all the file operations can't be performed.
To add security, write the tmp file to a path that's not accessible to the web browser.