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.'; } ?>
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.'".'; } ?>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.
