Перейти к содержимому

Как проверить существует ли файл

  • автор:

file_exists

На платформах Windows, для проверки наличия файлов на сетевых ресурсах, используйте имена, подобные //computername/share/filename или \\computername\share\filename .

Возвращаемые значения

Возвращает true , если файл или каталог, указанный параметром filename , существует, иначе возвращает false .

Замечание:

Данная функция возвращает false для символических ссылок, указывающих на несуществующие файлы.

Замечание:

Проверка происходит с помощью реальных UID/GID, а не эффективных идентификаторов.

Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Примеры

Пример #1 Проверка существования файла

if ( file_exists ( $filename )) <
echo «Файл $filename существует» ;
> else <
echo «Файл $filename не существует» ;
>
?>

Примечания

Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .

Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.

Смотрите также

  • is_readable() — Определяет существование файла и доступен ли он для чтения
  • is_writable() — Определяет, доступен ли файл для записи
  • is_file() — Определяет, является ли файл обычным файлом
  • file() — Читает содержимое файла и помещает его в массив
  • SplFileInfo

User Contributed Notes 31 notes

Note: The results of this function are cached. See clearstatcache() for more details.

That’s a pretty big note. Don’t forget this one, since it can make your file_exists() behave unexpectedly — probably at production time 😉

In response to seejohnrun’s version to check if a URL exists. Even if the file doesn’t exist you’re still going to get 404 headers. You can still use get_headers if you don’t have the option of using CURL..

$file = ‘http://www.domain.com/somefile.jpg’;
$file_headers = @get_headers($file);
if($file_headers[0] == ‘HTTP/1.1 404 Not Found’) <
$exists = false;
>
else <
$exists = true;
>

If the file being tested by file_exists() is a file on a symbolically-linked directory structure, the results depend on the permissions of the directory tree node underneath the linked tree. PHP under a web server (i.e. apache) will respect permissions of the file system underneath the symbolic link, contrasting with PHP as a shell script which respects permissions of the directories that are linked (i.e. on top, and visible).

This results in files that appear to NOT exist on a symbolic link, even though they are very much in existance and indeed are readable by the web server.

If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:

You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on «Open a session as» Create a new user that has enough permissions and also be sure that target share has the proper permissions.

Hope this save some hours of research to anyone.

With PHP 7.0 on Ubuntu 17.04 and with the option allow_url_fopen=On, file_exists() returns always false when trying to check a remote file via HTTP.

returns always «missing», even for an existing URL.

I found that in the same situation the file() function can read the remote file, so I changed my routine in

This is clearly a bit slower, especially if the remote file is big, but it solves this little problem.

file_exists() does NOT search the php include_path for your file, so don’t use it before trying to include or require.

@$result = include $filename;

Yes, include does return false when the file can’t be found, but it does also generate a warning. That’s why you need the @. Don’t try to get around the warning issue by using file_exists(). That will leave you scratching your head until you figure out or stumble across the fact that file_exists() DOESN’T SEARCH THE PHP INCLUDE_PATH.

NB: This function expects the full server-related pathname to work.

For example, if you run a PHP routine from within, for example, the root folder of your website and and ask:

You will get FALSE even if that file does exist off root.

You need to add

to get it to return TRUE — ie : /srv/www/mywebsite.com/public/images/Proofreading_patients.jpg

I wrote this little handy function to check if an image exists in a directory, and if so, return a filename which doesnt exists e.g. if you try ‘flower.jpg’ and it exists, then it tries ‘flower[1].jpg’ and if that one exists it tries ‘flower[2].jpg’ and so on. It works fine at my place. Ofcourse you can use it also for other filetypes than images.

<?php
function imageExists ( $image , $dir ) <

$i = 1 ; $probeer = $image ;

while( file_exists ( $dir . $probeer )) <
$punt = strrpos ( $image , «.» );
if( substr ( $image ,( $punt — 3 ), 1 )!==( «[» ) && substr ( $image ,( $punt — 1 ), 1 )!==( «]» )) <
$probeer = substr ( $image , 0 , $punt ). «[» . $i . «]» .
substr ( $image ,( $punt ), strlen ( $image )- $punt );
> else <
$probeer = substr ( $image , 0 ,( $punt — 3 )). «[» . $i . «]» .
substr ( $image ,( $punt ), strlen ( $image )- $punt );
>
$i ++;
>
return $probeer ;
>
?>

I was having problems with the file_exists when using urls, so I made this function:

<?php
function file_exists_2 ( $filePath )
<
return ( $ch = curl_init ( $filePath )) ? @ curl_close ( $ch ) || true : false ;
>
?>

Cheers!

You could use document root to be on the safer side because the function does not take relative paths:

<?php
if( file_exists ( $_SERVER < 'DOCUMENT_ROOT' >. «/my_images/abc.jpg» )) <
.
>
?>

Do not forget to put the slash ‘/’, e.g. my doc root in Ubuntu is /var/www without the slash.

Note on openspecies entry (excellent btw, thanks!).

If your server cannot resolve its own DNS, use the following:
$f = preg_replace(‘/www\.yourserver\.(net|com)/’, getenv(‘SERVER_ADDR’), $f);

Just before the $h = @get_headers($f); line.

Replace the extensions (net|com|. ) in the regexp expression as appropriate.

The preg_replace will effectively ‘resolve’ the address for you by assigning $f as follows:
http://10.0.0.125/myfile.gif

When using file_exists, seems you cannot do:

<?php
foreach ( $possibles as $poss )
<
if ( file_exists ( SITE_RANGE_IMAGE_PATH . $this -> range_id . ‘/ ‘ . $poss . ‘.jpg’ ) )
<
// exists
>
else
<
// not found
>
>
?>

so you must do:

<?php
foreach ( $possibles as $poss )
<
$img = SITE_RANGE_IMAGE_PATH . $this -> range_id . ‘/ ‘ . $poss . ‘.jpg’
if ( file_exists ( $img ) )
<
// exists
>
else
<
// not found
>
>
?>

Then things will work fine.

This is at least the case on this Windows system running php 5.2.5 and apache 2.2.3

Not sure if it is down to the concatenation or the fact theres a constant in there, i’m about to run away and test just that.

Older php (v4.x) do not work with get_headers() function. So I made this one and working.

<?php
function url_exists ( $url ) <
// Version 4.x supported
$handle = curl_init ( $url );
if ( false === $handle )
<
return false ;
>
curl_setopt ( $handle , CURLOPT_HEADER , false );
curl_setopt ( $handle , CURLOPT_FAILONERROR , true ); // this works
curl_setopt ( $handle , CURLOPT_NOBODY , true );
curl_setopt ( $handle , CURLOPT_RETURNTRANSFER , false );
$connectable = curl_exec ( $handle );
curl_close ( $handle );
return $connectable ;
>
?>

this code here is in case you want to check if a file exists in another server:

<?php
function fileExists ( $path ) <
return (@ fopen ( $path , «r» )== true );
>
?>

unfortunately the file_exists can’t reach remote servers, so I used the fopen function.

For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.

<?php
function url_exists ( $url ) <
$url = str_replace ( «http://» , «» , $url );
if ( strstr ( $url , «/» )) <
$url = explode ( «/» , $url , 2 );
$url [ 1 ] = «/» . $url [ 1 ];
> else <
$url = array( $url , «/» );
>

$fh = fsockopen ( $url [ 0 ], 80 );
if ( $fh ) <
fputs ( $fh , «GET » . $url [ 1 ]. » HTTP/1.1\nHost:» . $url [ 0 ]. «\n\n» );
if ( fread ( $fh , 22 ) == «HTTP/1.1 404 Not Found» ) < return FALSE ; >
else

file_exists() will return FALSE for broken links

$ ln -s does_not_exist my_link
$ ls -l
lrwxr-xr-x 1 user group 14 May 13 17:28 my_link -> does_not_exist
$ php -r «var_dump(file_exists(‘my_link’));»
bool(false)

Here is a simpler version of url_exists:

<?php
function url_exists ( $url ) <
$hdrs = @ get_headers ( $url );
return is_array ( $hdrs ) ? preg_match ( ‘/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/’ , $hdrs [ 0 ]) : false ;
>
?>

WordPress always prepends the full URL to any file it stores in its database so, as noted elsewhere, file_exists() can’t find the file since it uses the ‘document root’, not the URL. An easy way out of this is to use:

file_exists (str_replace (home_url(), $_SERVER[‘DOCUMENT_ROOT’], $file) )

to check if file $file exists. Note: As from PHP8, ‘DOCUMENT_ROOT’ must be enclosed within SQUARE BRACKETS, not braces as suggested by ferodano at gmail dot com

Or, if not using WP, replace home_url() above with the absolute URL name, eg. ‘https://mywebsite.com’ — within quotes and no trailing foreslash.

I made a bit of code that sees whether a file served via RTSP is there or not:

<?php
function rtsp_exists ( $url ) <

$server = parse_url ( $url , PHP_URL_HOST );
$port = «554» ;
$hdrs = «DESCRIBE » . $url . » RTSP/1.0″ . «\r\n\r\n» ;

//Open connection (15s timeout)
$sh = fsockopen ( $server , $port , $err , $err_otp , 15 );
//Check connections
if(! $sh ) return false ;
//Send headers
fputs ( $sh , $hdrs );
//Receive data (1KB)
$rtds = fgets ( $sh , 1024 );
//Close socket
fclose ( $sh );

return strpos ( $rtds , «200 OK» ) > 0 ;
>
?>

file_exists() is vulnerable to race conditions and clearstatcache() is not adequate to avoid it.

The following function is a good solution:

<?php
function file_exists_safe ( $file ) <
if (! $fd = fopen ( $file , ‘xb’ )) <
return true ; // the file already exists
>
fclose ( $fd ); // the file is now created, we don’t need the file handler
return false ;
>
?>

The function will create a file if non-existent, following calls will fail because the file exists (in effect being a lock).

IMPORTANT: The file will remain on the disk if it was successfully created and you must clean up after you, f.ex. remove it or overwrite it. This step is purposely omitted from the function as to let scripts do calculations all the while being sure the file won’t be «seized» by another process.

NOTE: This method fails if the above function is not used for checking in all other scripts/processes as it doesn’t actually lock the file.
FIX: You could flock() the file to prevent that (although all other scripts similarly must check it with flock() then, see https://www.php.net/manual/en/function.flock.php). Be sure to unlock and fclose() the file AFTER you’re done with it, and not within the above function:

<?php
function create_and_lock ( $file ) <
if (! $fd = fopen ( $file , ‘xb’ )) <
return false ;
>
if (! flock ( $fd , LOCK_EX | LOCK_NB )) < // may fail for other reasons, LOCK_NB will prevent blocking
fclose ( $fd );
unlink ( $file ); // clean up
return false ;
>
return $fd ;
>

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).

Проверить, существует ли файл в Java

В этом посте будет обсуждаться, как проверить, существует ли файл в Java.

При проверке существования файла возможны три результата:

  • Файл существует.
  • Файл не существует.
  • Статус файла неизвестен, так как у программы нет доступа к файлу.

Есть несколько способов проверить существование файла в Java. Каждое из следующих решений возвращает true, если файл существует; false в противном случае, когда файл не существует или его статус неизвестен.

Как проверить, существует ли файл или каталог в Bash

Часто при написании сценариев оболочки вы можете оказаться в ситуации, когда вам нужно выполнить действие в зависимости от того, существует файл или нет.

В Bash вы можете использовать команду test, чтобы проверить, существует ли файл, и определить тип файла.

Команда test принимает одну из следующих синтаксических форм:

Если вы хотите, чтобы ваш сценарий был переносимым, вам следует предпочесть старую команду test [ , которая доступна во всех оболочках POSIX. Новая обновленная версия тестовой команды [[ (двойные скобки) поддерживается в большинстве современных систем, использующих Bash, Zsh и Ksh в качестве оболочки по умолчанию.

Проверьте, существует ли файл

При проверке существования файла наиболее часто используются операторы FILE -e и -f . Первый проверит, существует ли файл независимо от типа, а второй вернет истину, только если ФАЙЛ является обычным файлом (а не каталогом или устройством).

Наиболее удобочитаемый вариант при проверке существования файла — использование команды test в сочетании с оператором if . Любой из приведенных ниже фрагментов проверит, существует ли файл /etc/resolv.conf :

Если вы хотите выполнить другое действие в зависимости от того, существует файл или нет, просто используйте конструкцию if / then:

Вы также можете использовать команду test без оператора if. Команда после оператора && будет выполнена только в том случае, если статус выхода тестовой команды — истина,

Если вы хотите запустить серию команд после оператора && просто заключите команды в фигурные скобки, разделенные ; или && :

Напротив && , оператор после || Оператор будет выполняться только в том случае, если статус выхода тестовой команды false .

Проверить, существует ли каталог

Операторы -d позволяют вам проверить, является ли файл каталогом или нет.

Например, чтобы проверить, существует ли каталог /etc/docker вы должны использовать:

Вы также можете использовать двойные скобки [[ вместо одинарной [ .

Проверьте, не существует ли файла

Как и во многих других языках, тестовое выражение может быть отменено с помощью ! (восклицательный знак) оператор логического НЕ:

То же, что и выше:

Проверьте, существует ли несколько файлов

Вместо использования сложных вложенных конструкций if / else вы можете использовать -a (или && с [[ ), чтобы проверить, существует ли несколько файлов:

Эквивалентные варианты без использования оператора IF:

Операторы проверки файлов

Команда test включает в себя следующие операторы FILE, которые позволяют проверять файлы определенных типов:

  • -b FILE — Истина, если ФАЙЛ существует и является специальным блочным файлом.
  • -c FILE — Истина, если ФАЙЛ существует и является файлом специальных символов.
  • -d FILE — Истина, если ФАЙЛ существует и является каталогом.
  • -e FILE — Истина, если ФАЙЛ существует и является файлом, независимо от типа (узел, каталог, сокет и т. д.).
  • -f FILE — Истина, если ФАЙЛ существует и является обычным файлом (не каталогом или устройством).
  • -G FILE — Истина, если ФАЙЛ существует и имеет ту же группу, что и пользователь, выполняющий команду.
  • -h FILE — Истина, если ФАЙЛ существует и является символической ссылкой.
  • -g FILE — Истина, если ФАЙЛ существует и для него установлен флаг set-group-id ( sgid ).
  • -k FILE — Истина, если ФАЙЛ существует и для него установлен флаг липкого бита.
  • -L FILE — Истина, если ФАЙЛ существует и является символической ссылкой.
  • -O FILE — Истина, если ФАЙЛ существует и принадлежит пользователю, выполняющему команду.
  • -p FILE — Истина, если ФАЙЛ существует и является каналом.
  • -r FILE — Истинно, если ФАЙЛ существует и доступен для чтения.
  • -S FILE — Истина, если ФАЙЛ существует и является сокетом.
  • -s FILE — Истина, если ФАЙЛ существует и имеет ненулевой размер.
  • -u FILE — Истинно, если ФАЙЛ существует и установлен флаг set-user-id ( suid ).
  • -w FILE — Истина, если ФАЙЛ существует и доступен для записи.
  • -x FILE — Истина, если ФАЙЛ существует и является исполняемым.

Выводы

В этом руководстве мы показали вам, как проверить, существует ли файл или каталог в Bash.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *