0

Would the file still have its previous contents correctly?

1)When error happened by using file_put_contents func

2)When error happened by using copy func

I'm asking because I want to implement semi-dynamic pages and I want to know if an error in this process can cause problem for the web page?

MTVS
  • 2,046
  • 5
  • 26
  • 37
  • 2
    It depends on a thousand different things, chief among which is the type of write being performed and the type of filesystem on which the file resides. – Jon Dec 05 '12 at 11:55
  • 1
    If you're worried about this stuff, write to temp file first and then rename it afterwards. – Ja͢ck Dec 05 '12 at 11:58
  • @Jon I'm asking because I want to implement semi-dynamic pages and I want to know if an error in this process can cause problem for the web page? – MTVS Dec 05 '12 at 11:58
  • 1
    @csstd: Most likely it can, and most likely you don't really care. If you did, you should be very busy reading advanced technical documentation on systems that can provide guarantees for this kind of eventuality. – Jon Dec 05 '12 at 12:02

1 Answers1

1

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.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
jmz
  • 5,399
  • 27
  • 29