Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if file exists and not directory

Tags:

php

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.

like image 211
John Magnolia Avatar asked Nov 19 '12 12:11

John Magnolia


People also ask

How do you check if a file exists in a directory PHP?

Use the file_exists() function to check if a file exists. Use the is_file() function to check if a path is a regular file, not a directory, and that file exists. Use the is_readable() function to check if a file exists and readable. Use the is_writable() function to check if a file exists and writable.

Is not a directory PHP?

The is_dir() function in PHP used to check whether the specified file is a directory or not. The name of the file is sent as a parameter to the is_dir() function and it returns True if the file is a directory else it returns False. Parameters Used: The is_dir() function in PHP accepts only one parameter.

What is Is_file function in PHP?

The is_file() function in PHP is an inbuilt function which is used to check whether the specified file is a regular file or not. The name of the file is sent as a parameter to the is_file() function and it returns True if the file is a regular file else it returns False.


1 Answers

You're looking for the is_file function:

public function exists() {
    return $this->_file !== null && is_file($this->_file);
}
like image 80
deceze Avatar answered Oct 21 '22 04:10

deceze