file_exists() or is_readable()

Co za asy... picture Co za asy... · Jul 7, 2011 · Viewed 13.8k times · Source

Which one should you use when you want to include a PHP file?

if(file_exists($file) require "$file";

or

if(is_readable($file) require "$file";

?

Answer

James picture James · Jun 5, 2015

file_exists() or is_readable()
Which one should you use when you want to include a PHP file?

This depends on if you want to know if only a file or a directory exists, or if either is fine, and if you need to check if readable or not.

Sometimes you only care the file and/or directory exist, and don't need to read, sometimes you also need to read.

Options

file_exists()

Checks whether a file or directory exists.

If you explicitly only want to know if a file exists, this will return false positives as will return true if it's a directory.

is_readable()

Tells whether a file or directory exists and is readable.

If you explicitly only want to know if a file is readable, this is likely to return false positives as could return true if it's a directory.


Additional options you've not mentioned, but probably need:

is_file()

Tells whether it exists and is a regular file (not a directory).

is_dir()

Tells whether it exists and is a directory (not a file).

Solution & Answer

If you want to check exists and:

  1. Is only a file: Use is_file()
  2. Is only a dir: Use is_dir()
  3. Is file or dir: Use file_exists()

If you want to check exists and is readable:

  1. And is only file: Use is_file() and is_readable()
  2. And is only dir: Use is_dir() and is_readable()
  3. And is file or dir: Use is_readable()

You don't need to use file_exists() and is_readable() together because is_readable() also checks if file_exists().
Pairing is_readable() with either is_file() or is_dir() is only to check if is readable specifically on a file only or specifically on a directory only.


Relying on require

As with most PHP and "what is the best approach/function/etc" - it depends on the scenario.

Relying on just require to manage if the system hangs or not is not really useful. Imagine the required file is not available, so PHP halts as require fails, but the file is simply an article image or user avatar - do you really not want to serve site navigation, logo, links, all kinds of page text and content just because of a missing article image?

VITAL:
If the file is a database connection class, which allows serving of the entire page content, then the file not being there likely requires a system halt.
Of course then you should have some kind of exit strategy, such as serving a 404 page, or an error message - "Sorry there was a fault, we will look into it" etc.

NON VITAL:
It's sometimes valid for the file to not exist, or at least not detrimental to the rest of the application.
Such as if an image file does not exist, you could serve a message or default image, such as a user avatar will just have a default avatar if theirs is not found.