Search code examples
phpcopyfile-put-contents

PHP copy vs file_put_contents


I got access to both a path and content, both as strings.

I want to copy the content from one place to another. I can use copy or file_put_contents. They are different functions but in my case they will result in the same thing.

Are there any advantages with using one over the other? Is some of the faster, more reliable etc?

Path

/some/path/to/file.txt

Content

Some content

References


Solution

  • Yes, return values of copy() are less ambigous.

    Both of them are using the same stream copy function, but in order to use file_put_contents() to copy files, the data must be read to memory beforhand.

    So it is very likely that the latter is slower than copy(), at least in mass copy.

    Also be advised that file_put_contents() can return values which could be interpreted as FALSE, even if it succeeded (for example, it will return 0 if you just use it to create an empty file.) So always use the "identical" comparison operator (===) to check the result of the function.