is_file() and file_exists() in PHP

  • Avinash
  • 2
  • Sep 20, 2011
  • Web Development

These both functions are used to check the existence of the file. But there is a minor difference between these functions.

Let’s see what’s the difference.

1) file_exists()

This function takes the path as a parameter and return TRUE or FALSE. This function will return TRUE in case of file exists and FALSE in case if file is not exists. Check below code for more details.

$path ="/path/to/file/text.txt"; if(file_exists($path)) echo "File Exists"; else echo "File not Exists";
  $path ="/path/to/file/text.txt";
  if(file_exists($path))
    echo "File Exists";
  else
    echo "File not Exists";

On more thing is that this function will return TRUE if you pass the path for the valid directory also. Check below code,

$path ="/path/to/file"; if(file_exists($path)) echo "File Exists"; else echo "File not Exists"; // This will return true if given path is a valid directory
  $path ="/path/to/file";
  if(file_exists($path))
    echo "File Exists";
  else
    echo "File not Exists";

// This will return true if given path is a valid directory

2) is_file()

Unlike file_exists(), is_file() function will check only for the valid files. If we pass the valid path to any directory then it will return FALSE.

Check below code:

$path=/path/to/file/text.txt; is_file($path); // Return TRUE if valid file $path=/path/to/directory; is_file($path); # Return FALSE every time
  $path=/path/to/file/text.txt;
  is_file($path);
  // Return TRUE if valid file
 
  $path=/path/to/directory;
  is_file($path);
  # Return FALSE every time

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by:

  • http://www.pure-tentation.fr syndrael

    That’s why is_dir function exists..

  • http://ocportal.com/ Chris Graham

    Also worth noting is is_file is twice as fast, so it’s a good optimisation if you know it’s a real file you’re checking. Seems bizarre, but I guess file_exists actually runs multiple checks for possible scenarios, each of which might return true.