17

I read the file_exists() can also return turn if it points to a directory. What is the fastest way to check if only a file exits?

At the moment I have:

/**
 * Check if the file exists.
 *
 * @return bool
 */
public function exists() {
    if(is_null($this->_file)) return false;

    return (!is_dir($this->_file) && file_exists($this->_file)) ? true : false;
}

I found lots of posts relating to checking if file exits in PHP but nothing that talks about the directory and how best to check this.

This method can get called 1000s of time so I could really do with making it as fast as possible.

1
  • 1
    What result should you get for symlinks to files? Commented Nov 19, 2012 at 12:22

3 Answers 3

32

You're looking for the is_file function:

public function exists() {
    return $this->_file !== null && is_file($this->_file);
}
Sign up to request clarification or add additional context in comments.

4 Comments

From the docs: "Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB." Is this anything to worry about? 99% of the time no file will ever reach this size unless its a log file out of control
Also this puts me off using is_file php.net/manual/en/function.is-file.php#46845
@John Hard to say. Some may return unexpected results... I have not encountered a case where this was a problem. YMMV.
@John And that second concern is pretty nonsensical, since that works the same for all relative paths in all functions. Which is why you typically want to avoid using relative paths.
4
public function exists() {
    return !is_dir($this->_file) && file_exists($this->_file);
}

Comments

0

You can try this for file only. Its a custom function you will call instead of file_exists function

 function custom_file_exists($filePath)
    {
          if((is_file($filePath))&&(file_exists($filePath))){
            return true;
          }   
          return false;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.