PHP: Avoid File_Get_Contents and File_Put_Contents

Why you may want to reconsider your use of PHP file- functions

1071 views
d

By. Jacob

Edited: 2019-12-02 22:51

file_get_contents, PHP tutorial

It is generally not recommended to rely on the bare- file functions in PHP, and I will briefly list the reasons in this article.

Using functions such as file_get_contents or file_put_contents is bad for several reasons. The problem is that they are often used incorrectly, or developers tend to have poor implementations of them. The file functions can be used to carry out read and write operations in the file system, but this is not without problems.

I have already covered the problem with concurrency in this article, but I did not think of all the other reasons until recently.

Here is a list of all the reasons I could think off:

  1. The bare file functions can be dangerous to use if you have concurrent users.
  2. No support for the HTTP Range header
  3. No support for caching.
  4. No file read buffering, resulting in high memory use with file_get_contents.
  5. Content-length is not supported.
  6. Content-type is not supported.
  7. Poor or no error handling. I.e. Does the file even exist?

Instead of trying to implement all of this yourself, you can use the Beamtic File Handler library.

I started work on the File Handler after I became frustrated that I was constantly re-writing file operations without taking care to solve the concurrency problem, and properly handle all the different error cases. Later I decided to release it on GitHub, and I am still actively maintaining it.

Tell us what you think: