Home  >  Article  >  Backend Development  >  How to check if file exists in PHP

How to check if file exists in PHP

PHPz
PHPzOriginal
2023-08-26 12:29:231720browse

How to check if file exists in PHP

Many times, you need to move files in PHP or store some data in them. In either case, knowing in advance whether the file exists can help us avoid some unexpected behavior.

PHP comes with a variety of functions to handle different types of queries related to files. In this tutorial, I will give you a brief overview of all these features so that you can choose the one that best suits your situation.

Importance of checking whether the file exists

In many cases it may be important to check whether a file exists before performing other operations. Let's say your website allows users to upload image files to your server for later access. It's fair to assume that if many users are using your service to frequently upload multiple files, there's always the possibility of filename conflicts.

In this case, it becomes important to check if another file already exists in the location where you want to save the user's most recently uploaded file. You can then choose to take steps such as renaming the file to something else or letting users know that their upload will overwrite the existing file.

Let's consider another scenario where you should append data to a file in PHP. If the file you created to write all your data to is deleted for some reason, a function like file_put_contents() will just create a new file with the specified name and store your data in in the newly created file. This may be desirable in some cases, but this is not always the case. So if you already expect the file to exist before you start writing data, it makes sense to check if the file exists ahead of time.

Check if file exists in PHP

You can use three different functions to check if a file exists in PHP.

The first function is file_exists(). This function accepts one parameter, which is the path where the file is located. Remember, it returns true for existing files and directories. This may or may not be sufficient for your needs.

If you want to ensure that the specified path points to a file rather than a directory, consider using the is_file() function. Likewise, you can use the is_dir() function to check if the path you specify exists and points to a directory.

<?php

$name = "squares.txt";
$directory = "squares.zip";

if(file_exists($name)) {
    echo 'The file "'.$name.'" exists.';
}

if(is_file($name)) {
    echo '"'.$name.'" is indeed a file.';
}

if(is_dir($directory)) {
    echo '"'.$directory.'" turned out to be a directory.';
}

?>
output
The file "squares.txt" exists.
"squares.txt" is indeed a file.
"squares.zip" turned out to be a directory.

In the example above, I intentionally named one of the directories squares.zip to show that it is important to do your own checks and not assume that the filename provided is actually a filename or directory.

It is important to remember that both is_file() and is_dir() will return false even if the parent directory does not have the correct permissions for the path that actually exists is also like this.

Check if the file exists and is readable and writable

Two other functions named is_read() and is_writable() can be used to obtain some additional information about the file in addition to checking whether the file exists.

As the name suggests, the is_read() function will check two things: first, the file or directory actually exists, and second, the file is readable. Likewise, the is_writable() function also checks two things, that the file or directory exists and is writable.

<?php

$name = "squares.txt";

if(is_readable($name)) {
    echo 'We can read "'.$name.'".';
}

if(is_writable($name)) {
    echo 'We can also modify the contents of "'.$name.'".';
}

?>
output
We can read "squares.txt". 
We can also modify the contents of "squares.txt".

I recommend that you be careful when interpreting the return values ​​of these two functions. For example, when is_read() returns false, our first instinct is to think that the file we are querying is not readable. However, this function also returns false if the file does not exist. It is important to always keep this aspect of these features in mind.

Beware of cached results

The return values ​​returned by calling all five functions, namely file_exists(), is_file(), is_dir(), is_read( ) and is_writeable()—Cached. This means that repeated calls to a function (such as is_file()) may show stale results.

PHP caches the results of these functions to improve performance. This ensures that multiple calls querying the same file run faster. However, even if the files change during script execution, their return values ​​will remain the same.

Only cache results for files that already exist. This means that calling the function is_file() will continue to return false for a file that does not exist, but will start returning true once the file is created. On the other hand, for files that existed during the first call, the function will continue to return true, even if the file has been deleted.

<?php

$name = "squares.txt";

if(is_file($name)) {
    echo '"'.$name.'" is indeed a file.';
}


// Manually delete the file while script waits.
sleep(5);

if(is_file($name)) {
    echo '"'.$name.'" is indeed a file.';
}

clearstatcache();

if(is_file($name)) {
    echo '"'.$name.'" is indeed a file.';
} else {
    echo 'The file probably no longer exists.';
}

?>

If you run the above code snippet against a file that actually exists and then manually delete it while the script waits, calling is_file() will still return true. However, just calling clearstatcache() before querying again to see if the file exists will give you the correct results.

输出
"squares.txt" is indeed a file.
"squares.txt" is indeed a file.
The file probably no longer exists.

要记住的另一件事是,调用 unlink() 会自动清除缓存,因此稍后调用 is_file() 等函数时会得到新的结果。

最终想法

本教程首先介绍了检查 PHP 中文件是否存在的重要性。之后,我们了解了可用于检查 PHP 中文件是否存在的不同函数。我们还了解了其中一些功能可能具有的优点和缺点。

正如我在最后提到的,PHP 将缓存其中一些函数调用的结果以提高性能。因此,请确保在对这些文件执行重要操作之前清除缓存。

The above is the detailed content of How to check if file exists in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more