John Magnolia
John Magnolia

Reputation: 16793

PHP check if file exists and not directory

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.

Upvotes: 17

Views: 17032

Answers (3)

Faruk Omar
Faruk Omar

Reputation: 1193

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;
    }

Upvotes: 0

looper
looper

Reputation: 1979

public function exists() {
    return !is_dir($this->_file) && file_exists($this->_file);
}

Upvotes: 4

deceze
deceze

Reputation: 522005

You're looking for the is_file function:

public function exists() {
    return $this->_file !== null && is_file($this->_file);
}

Upvotes: 32

Related Questions