Fwrite vs file_put_contents

Hi,

Which one would be faster and easier on the server? I have a script that rights to a file ever second or so, and when constantly done it empties the file.

Someone suggested switching over to file_put_contents?

Thank you for your input.

My preference when coding is file_put_contents.

According to the manual file_put_contents() is “Identical to calling fopen(), fwrite(), and fclose() successively.”… so I suppose if you are writing to the file several times in the same script fwrite() would be better, as it doesn’t have to keep opening and closing the file. If you just need to write once then they are identical

That’s unfortunate :frowning:

You might want to do some research and see if file_put_contents() caches connections and only closes them at the end. My experience with file_get_contents() is that fopen(), fread(), and fclose() is slightly faster – though I have no clue why and it really shouldn’t be.

Sorry. I didn’t realise he would be writing to the file consectuively :blush:

I don’t see how caching the connection would help considering hundreds of files are being written to, perhaps 5-10 a second.

PHP may not close the file until the script ends or some other condition is met, such as too many files open. So succeeding calls to file_put_contents() may not need to do an fopen(). This is only conjecture on my part though. But I know that PHP tries internally to be smart when dealing with files.

It’s opening different files, though. Therefore keeping the file open would not be an option.

Thanks

So really, the only way to run successfully a script like this would be to move to a dedicated server?

if its writing to different files then fopen() fwrite() and fclose() and file_put_contents() are identical: php.net/file_put_contents