- PHP File Exists
- Check if a file exists using the file_exists() function
- Check if a file exists using the is_file() function
- Check if a file exists and readable
- Check if a file exists and writable
- Summary
- file_exists
- Возвращаемые значения
- Примеры
- Ошибки
- Примечания
- Смотрите также
- File path exist in php
- PHP FTP Functions
- PHP JASON
- PHP Math Functions
- PHP GMP Functions
- PHP MySQLi Functions
- PHP String Functions
- PHP Network Functions
- PHP IntlChar Functions
- PHP Image Processing and GD Functions
- PHP Gmagick Functions
- PHP Imagick Functions
- PHP ImagickDraw Functions
- PHP DsDeque Functions
- PHP DsMap Functions
- PHP DSSequence Functions
- PHP DSVector Functions
- PHP DsStack Functions
- PHP DsQueue Functions
- PHP DsPriorityQueue Functions
- PHP SPL Data structures
- PHP Basics
- PHP Advance
- PHP Array Functions
- PHP Calendar Functions
- PHP Date/Time Functions
- PHP Directory Functions
- PHP Error
- PHP FTP Functions
- PHP JASON
- PHP Math Functions
- PHP GMP Functions
- PHP MySQLi Functions
- PHP String Functions
- PHP Network Functions
- PHP IntlChar Functions
- PHP Image Processing and GD Functions
- PHP Gmagick Functions
- PHP Imagick Functions
- PHP ImagickDraw Functions
- PHP DsDeque Functions
- PHP DsMap Functions
- PHP DSSequence Functions
- PHP DSVector Functions
- PHP DsStack Functions
- PHP DsQueue Functions
- PHP DsPriorityQueue Functions
- PHP SPL Data structures
PHP File Exists
Summary: in this tutorial, you will learn how to check if a file exists in PHP using the file_exists() , is_file() , is_readable() , and is_writable() functions.
PHP provides some useful functions that allow you to check if a file exists. Let’s examine these functions and how to use them effectively.
Check if a file exists using the file_exists() function
To check if a file exists, you use the file_exist() function:
file_exists ( string $filename ) : bool
Code language: PHP (php)
The file_exists() function accepts a filename and returns true if the file exists; otherwise it returns false .
The following example uses the file_exists() function to check if the file readme.txt exists in the current directory:
$filename = 'readme.txt'; if (file_exists($filename)) < $message = "The file $filename exists"; > else < $message = "The file $filename does not exist"; > echo $message;
Code language: HTML, XML (xml)
If the readme.txt exists in the same directory of the script, you’ll see the following message:
The file readme.txt exists
Code language: CSS (css)
…otherwise, you’ll see a different message:
The file readme.txt does not exist
Code language: CSS (css)
Note that the $filename can be also a path to a directory. In this case, the file_exists() function returns true if the directory exists.
Check if a file exists using the is_file() function
If you want to check if a path is a file (not a directory) and exists in the file system, you can use the is_file() function.
The is_file() function accepts a $filename and returns true if the $filename is a file and exists:
is_file ( string $filename ) : bool
Code language: PHP (php)
The following example uses the is_file() function to check if the file readme.txt exists:
$filename = 'readme.txt'; if (is_file($filename)) < $message = "The file $filename exists"; > else < $message = "The file $filename does not exist"; > echo $message;
Code language: HTML, XML (xml)
Check if a file exists and readable
In practice, you often want to check if a file exists before reading its contents. To check if a file exists and is readable, you use the is_readable() function:
is_readable ( string $filename ) : bool
Code language: PHP (php)
The is_readable() function returns true if the $filename exists and readable, or false otherwise. Note that the $filename can be a directory.
The following example uses the is_readable() function to check if the readme.txt file exists and readable:
$filename = 'readme.txt'; if (is_readable($filename)) < $message = "The file $filename exists"; > else < $message = "The file $filename does not exist"; > echo $message;
Code language: HTML, XML (xml)
Check if a file exists and writable
Before writing to a file, you need to check the file exists and is writable. In this case, you can use the is_writable() function:
is_writable ( string $filename ) : bool
Code language: PHP (php)
The is_writable() function returns true if the $filename exists and writable, or false otherwise.
The following example uses the is_writable() function to check the readme.txt file exists and writable:
$filename = 'readme.txt'; if (is_writable($filename)) < $message = "The file $filename exists"; > else < $message = "The file $filename does not exist"; > echo $message;
Code language: HTML, XML (xml)
Summary
- 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.
file_exists
На платформах Windows, для проверки наличия файлов на сетевых ресурсах, используйте имена, подобные //computername/share/filename или \\computername\share\filename .
Возвращаемые значения
Возвращает TRUE , если файл или каталог, указанный параметром filename , существует, иначе возвращает FALSE .
Замечание:
Данная функция возвращает FALSE для символических ссылок, указывающих на несуществующие файлы.
Если файлы недоступны из-за ограничений, налагаемых безопасным режимом, то данная функция вернет FALSE . Однако, эти файлы все еще могут быть подключены, если они располагаются в каталоге safe_mode_include_dir.
Замечание:
Проверка происходит с помощью реальных UID/GID, а не эффективных идентификаторов.
Замечание: Так как тип integer в PHP является целым числом со знаком и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2ГБ.
Примеры
Пример #1 Проверка существования файла
if ( file_exists ( $filename )) echo «Файл $filename существует» ;
> else echo «Файл $filename не существует» ;
>
?>
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Примечания
Замечание: Результаты этой функции кэшируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обертками url. Список оберток, поддерживаемых семейством функций stat() , смотрите в Поддерживаемые протоколы и обработчики (wrappers).
Смотрите также
- is_readable() — Определяет существование файла и доступен ли он для чтения
- is_writable() — Определяет, доступен ли файл для записи
- is_file() — Определяет, является ли файл обычным файлом
- file() — Читает содержимое файла и помещает его в массив
File path exist in php
- PHP basename( ) Function
- PHP chgrp( ) Function
- PHP chmod( ) Function
- PHP chown( ) Function
- PHP copy( ) Function
- PHP dirname( ) Function
- PHP disk_free_space( ) Function
- PHP disk_total_space( ) Function
- PHP feof( ) Function
- PHP fflush( ) Function
- PHP | fgetc( ) Function
- PHP | fgets( ) Function
- PHP | fgetss( ) Function
- PHP | file_exists( ) Function
- PHP file_get_contents() Function
- PHP Filesystem Functions Complete Reference
PHP FTP Functions
- PHP | ftp_alloc() function
- PHP | ftp_chdir() function
- PHP | ftp_close() function
- PHP | ftp_connect() function
- PHP | ftp_delete() function
- PHP | ftp_exec() function
- PHP | ftp_get() function
- PHP | ftp_put() function
- PHP | ftp_get_option() function
- PHP | ftp_login() function
- PHP | ftp_mdtm() Function
- PHP | ftp_mkdir() function
PHP JASON
PHP Math Functions
PHP GMP Functions
PHP MySQLi Functions
PHP String Functions
PHP Network Functions
PHP IntlChar Functions
PHP Image Processing and GD Functions
PHP Gmagick Functions
PHP Imagick Functions
PHP ImagickDraw Functions
PHP DsDeque Functions
PHP DsMap Functions
- PHP | Ds\Map allocate() Function
- PHP | Ds\Map apply() Function
- PHP | Ds\Map capacity() Function
- PHP | DS\Map clear() Function
- PHP | Ds\Map __construct() Function
- PHP Ds\Map copy() Function
- PHP | Ds\Map count() Function
- PHP | Ds\Map diff() Function
- PHP | Ds\Map filter() Function
- PHP | Ds\Map first() Function
- PHP Ds\Map Functions Complete Reference
PHP DSSequence Functions
PHP DSVector Functions
PHP DsStack Functions
PHP DsQueue Functions
PHP DsPriorityQueue Functions
PHP SPL Data structures
- SplDoublyLinkedList in PHP
- PHP SplDoublyLinkedList add() Function
- PHP SplDoublyLinkedList bottom() Function
- PHP SplDoublyLinkedList count() function
- PHP SplFixedArray count() Function
- PHP SplFixedArray current() Function
- PHP SplFixedArray getSize() Function
- PHP SplFixedArray key() Function
- PHP SplObjectStorage addAll() Function
- PHP SplObjectStorage attach() Function
- PHP SplObjectStorage contains() Function
- PHP SplObjectStorage count() Function
- PHP SplQueue::__construct() Function
- PHP SPL Data structures Complete Reference
PHP Basics
- PHP Tutorial
- PHP | Introduction
- PHP Full Form
- How to set PHP development environment in windows ?
- LAMP installation and important PHP configurations on Ubuntu
- PHP | Coding Standards
- PHP | Basic Syntax
- PHP | Variables
- PHP echo and print
- PHP | Data Types
- PHP | Strings
- PHP | Constants
- PHP | Magic Constants
- PHP | Decision Making
- PHP | Loops
- PHP | Superglobals
- PHP | Regular Expressions
- PHP Examples
PHP Advance
- Describe PHP Include and Require
- PHP | Basics of File Handling
- PHP | fopen( ) (Function open file or URL)
- PHP fread( ) Function
- PHP fclose( ) Function
- PHP | fwrite( ) Function
- PHP | Uploading File
- PHP Cookies
- PHP | Sessions
- PHP Filter and Filter Constant
- Implementing callback in PHP
- Exception Handling in PHP
PHP Array Functions
- PHP | Arrays
- PHP array() Function
- PHP | array_change_key_case() Function
- PHP array_chunk() Function
- PHP | array_column() Function
- PHP array_combine() Function
- PHP array_count_values() Function
- PHP array_diff() function
- PHP array_diff_assoc() Function
- PHP array_diff_key() Function
- PHP array_diff_uassoc() Function
- PHP array_diff_ukey() Function
- PHP array_fill() function
- PHP array_fill_keys() Function
- PHP Array Functions Complete Reference
PHP Calendar Functions
PHP Date/Time Functions
- PHP Date and Time
- PHP | checkdate() Function
- PHP | date_create(), date_format(), date_add() Functions
- PHP | date_create_from_format() Function
- PHP | date_date_set() Function
- PHP | date_default_timezone_get() Function
- PHP | date_default_timezone_set() Function
- PHP | date_diff() Function
- PHP | date_get_last_errors() Function
- PHP | date_isodate_set() Function
- PHP | date_modify() Function
- PHP | date_offset_get() Function
- PHP | date_parse_from_format() Function
- PHP | date_parse() Function
- PHP | date_sub() Function
PHP Directory Functions
PHP Error
- PHP basename( ) Function
- PHP chgrp( ) Function
- PHP chmod( ) Function
- PHP chown( ) Function
- PHP copy( ) Function
- PHP dirname( ) Function
- PHP disk_free_space( ) Function
- PHP disk_total_space( ) Function
- PHP feof( ) Function
- PHP fflush( ) Function
- PHP | fgetc( ) Function
- PHP | fgets( ) Function
- PHP | fgetss( ) Function
- PHP | file_exists( ) Function
- PHP file_get_contents() Function
- PHP Filesystem Functions Complete Reference
PHP FTP Functions
- PHP | ftp_alloc() function
- PHP | ftp_chdir() function
- PHP | ftp_close() function
- PHP | ftp_connect() function
- PHP | ftp_delete() function
- PHP | ftp_exec() function
- PHP | ftp_get() function
- PHP | ftp_put() function
- PHP | ftp_get_option() function
- PHP | ftp_login() function
- PHP | ftp_mdtm() Function
- PHP | ftp_mkdir() function
PHP JASON
PHP Math Functions
PHP GMP Functions
PHP MySQLi Functions
PHP String Functions
PHP Network Functions
PHP IntlChar Functions
PHP Image Processing and GD Functions
PHP Gmagick Functions
PHP Imagick Functions
PHP ImagickDraw Functions
PHP DsDeque Functions
PHP DsMap Functions
- PHP | Ds\Map allocate() Function
- PHP | Ds\Map apply() Function
- PHP | Ds\Map capacity() Function
- PHP | DS\Map clear() Function
- PHP | Ds\Map __construct() Function
- PHP Ds\Map copy() Function
- PHP | Ds\Map count() Function
- PHP | Ds\Map diff() Function
- PHP | Ds\Map filter() Function
- PHP | Ds\Map first() Function
- PHP Ds\Map Functions Complete Reference
PHP DSSequence Functions
PHP DSVector Functions
PHP DsStack Functions
PHP DsQueue Functions
PHP DsPriorityQueue Functions
PHP SPL Data structures
- SplDoublyLinkedList in PHP
- PHP SplDoublyLinkedList add() Function
- PHP SplDoublyLinkedList bottom() Function
- PHP SplDoublyLinkedList count() function
- PHP SplFixedArray count() Function
- PHP SplFixedArray current() Function
- PHP SplFixedArray getSize() Function
- PHP SplFixedArray key() Function
- PHP SplObjectStorage addAll() Function
- PHP SplObjectStorage attach() Function
- PHP SplObjectStorage contains() Function
- PHP SplObjectStorage count() Function
- PHP SplQueue::__construct() Function
- PHP SPL Data structures Complete Reference