Php существует ли файл

Обновлено: 04.07.2024

File_exists - это функция в php, которая определяет есть ли - существует ли файл по тому пути, который вы указали:

Синтаксис функции file_exists

Давайте попробуем разобрать синтаксис функции file_exists

file_exists - название функции.

string - тип принимаемых данных функцией file_exists - строка.

$filename - название файла разрешением, либо путь до файла.

: bool - тип возвращаемого значения булев.

Как проще написать функцию file_exists

Как переводится file_exists.

Словосочетание File_exists- состоит двух английских слов

File - переводится как файл и

exists - переводится как существует .

Итого, если брать словосочетание file exists, то оно переводится скорее с вопросительным смыслом!

File already exists перевод

Очень часто вместе с file_exists идет словосочетание File already exists и многих интересует, как это переводится!?
File already exists -переводится, как файл уже существует!

Что возвращает file_exists

Для того, чтобы работать с функцией надо понимать, что возвращает функция! Поскольку file_exists предполагает два ответа, да - существует, нет - не существует, то логично, что она должна такие же данные возвращать и в php!
File_exists - возвращает в случае существования файла true, иначе false - подробнее.

Как получить возвращаемые значения относительно файла в file_exists

Для иллюстрации работы функции file_exists нам потребуется два файла, один из которых не будет существовать!

Для получения того, что возвращает функция file_exists - нам потребуется другая функция -> var_dump

Применим её к file_exists таким образом:

$home = $_SERVER["DOCUMENT_ROOT"];//путь до корневой папки

$file = "/index.html"; //главная страница сайта

Результат возврата функции file_exists к существующему файлу

Как видим, file_exists возвращает значение "true", а тип булев - как мы и говорили в синтаксисе(см.выше):

Тоже самое проделаем с файлом, который не существует! Внутри неважно что мы напишем, должно быть единственное условие, что файла не существует:

Результат возврата функции file_exists к не существующему файлу

Всего три варианта проверки file_exists

Если вы прочитаете аннотацию к функции file_exists, то могу с точностью сказать, что у вас возникнут как минимум 3 вопроса(просто . там этого не будет написано..):

Вообще существует, как минимум 3 варианта написания пути к файлу, это:

Локально(поскольку данным вариантом пути я никогда не пользуюсь, то и смыслы писать о нём нет).

Далее. в подробностях рассмотрим эти три варианта!

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

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

Если у вас на сайте единая точка входа, и оба файла подчинены этому, то file_exists вернет "true" хотя должен вернуть "false"(при отсутствующем файле. )

Нужен пример!? легко!

Если мы сейчас посмотрим в адресную строку, то мы увидим вот это:

Напишем адрес для файла, который " НЕ СУЩЕСТВУЕТ! ", который якобы лежит в этой же папке, что и данная страница. Вы можете нажать на ссылку, проверить существует ли файл на самом деле! Сайт вам вернет 404 - т.е. подтвердит, что файла по данному адресу в данной папке нет.

Другими словами, проверка существования локально "file_exists" - должна вернуть "false"!

Давайте выведем этот код прямо здесь:

- Парадокс!? Нет! Объясняется просто!

Все файлы и в том числе обрабатывающие, стекаются в одну точку -> на главную в нашем случае -> index.html(при соответствующих настройках htaccess, файл можно менять), при единой точке входа. И для скрипта проверять существование файла index.html - это проверка самого себя, как бы странно это не звучало.

Чтобы вы понимали, именно проверять таким образом локально, в приведенном примере, корневая папка, будет той локальной папкой для этой проверки существования файла!

Все файлы, например sitemap.xml, которые будут физически находиться в корневой папке сайта, file_exists будет возвращать true!


Проделаем тоже относительно нашего файла, на котором данный текст

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

Первый файл - это данный файл и мы расположим здесь вот такую запись.

var_dump (file_exists('003_proverit_suschestvuet_li_fayl_php_file_exists.html'));

И второй файл. на котором расположим точно такую же запись, кроме названия самого файла.

Два идентичных кода с использованием функции file_exists.

Расположенных на файлах отличающихся правилом обработки единая точка входа

Будут давать противоположные ответы.

Проверка существования файла по абсолютному пути file_exists

Нам потребуется получить абсолютный путь до файла, из адресной строки и чтобы данный файл существовал! Сделаем такой специальный файл ->file_exists_ok.dat, на котором и будем испытывать функцию file_exists

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

Как видим, казалось бы, файл существует, но функция file_exists возвращает false. И вывод единственный, что получить реальное положение дел относительно существования файла по абсолютному пути - не представляется возможным!

Проверка существования файла по пути на сервере file_exists

Теперь возьмем тоже самый существующий файл и применим уже не абсолютный путь, а путь на сервере до файла и вставим его в в функцию file_exists

var_dump (file_exists( $home.'/__a-data/__all_for_scripts/__examples/php/file_exists/file_exists_ok.dat'));

И получим результат работы функции file_exists :

Вывод о существовании файла и функции file_exists

Какой вывод можно сделать по тем проверкам существования или отсутствия файла на сервере!?

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Return Values

Returns true if the file or directory specified by filename exists; false otherwise.

Note:

This function will return false for symlinks pointing to non-existing files.

Note:

The check is done using the real UID/GID instead of the effective one.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

if ( file_exists ( $filename )) echo "The file $filename exists" ;
> else echo "The file $filename does not exist" ;
>
?>

Notes

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

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_readable() - Tells whether a file exists and is readable
  • is_writable() - Tells whether the filename is writable
  • is_file() - Tells whether the filename is a regular file
  • file() - Reads entire file into an array
  • SplFileInfo

User Contributed Notes 30 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 ;)

Note that realpath() will return false if the file doesn't exist. So if you're going to absolutize the path and resolve symlinks anyway, you can just check the return value from realpath() instead of calling file_exists() first I needed to measure performance for a project, so I did a simple test with one million file_exists() and is_file() checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file() needed 3.0 for scenario one and 3.3 seconds for scenario two. file_exists() needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists() is faster.

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.

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

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.

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.

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

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 ;
>
?>

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.

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.

Note that this will return false for streams, eg, php://stdin.

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.

Here is a simpler version of url_exists:

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.

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!

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 ;
>
?>

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

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 ;
>
?>

file_exists will have trouble finding your file if the file permissions are not read enabled for 'other' when not owned by your php user. I thought I was having trouble with a directory name having a space in it (/users/andrew/Pictures/iPhoto Library/AlbumData.xml) but the reality was that there weren't read permissions on Pictures, iPhoto Library or AlbumData.xml. Once I fixed that, file_exists worked.

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)

Great alternative to file_exists() is stream_resolve_include_path()

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.

I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.

It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.

<?PHP
// .htaccess php_value include_path '/home/user/public_html/';

// includes lies in /home/user/public_html/includes/

//doesn't work, file_exists returns false
if ( file_exists ( 'includes/config.php' ) )
include( 'includes/config.php' );
>

//does work, file_exists returns true
if ( file_exists ( '/home/user/public_html/includes/config.php' ) )
include( 'includes/config.php' );
>
?>

Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.

The code can be used to t a filename that can be used to create a new filename.

<?php
function generateRandomString ( $length = 8 )
<
$string = "" ;

//character that can be used
$possible = "0123456789bcdfghjkmnpqrstvwxyz" ;

for( $i = 0 ; $i < $length ; $i ++)
<
$char = substr ( $possible , rand ( 0 , strlen ( $possible )- 1 ), 1 );

if (! strstr ( $string , $char ))
<
$string .= $char ;
>
>

function randomFile ( $folder = '' , $extension = '' )
<
$folder = trim ( $folder );
$folder = ( $folder == '' ) ? './' : $folder ;

//check if directory exist
if (! is_dir ( $folder ))

//generate a filepath
$filepath = $folder . "/" . generateRandomString ( 128 ) . $extension ;

//check if that filepath already exist, if it exist if generates again
//till if gets one that doesn't exist
while( file_exists ( $filepath ))
<
$filepath = $folder . "/" . generateRandomString ( 128 ) . $extension ;
>

My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):

<?php
function __autoload ( $name )
<
$path = explode ( ":" , ini_get ( 'include_path' )); //get all the possible paths to the file (preloaded with the file structure of the project)
foreach( $path as $tryThis )
<
//try each possible iteration of the file name and use the first one that comes up
// name.class.php first
$exists = file_exists ( $tryThis . '/' . $name . '.class.php' );
if ( $exists )
<
include_once( $name . '.class.php' );
return;
>

//ok that didn't work, try the other way around
$exists = file_exists ( $tryThis . '/' . 'class.' . $name . '.php' );
if ( $exists )
<
include_once( 'class.' . $name . '.php' );
return;
>

//neither did that. let's try as an inc.php
$exists = file_exists ( $tryThis . '/' . $name . '.inc.php' );
if ( $exists )
<
include_once( $name . '.inc.php' );
return;
>
>


// can't find it.
die( "Class $name could not be found!" );
>
?>

The following script checks if there is a file with the same name and adds _n to the end of the file name, where n increases. if img.jpg is on the server, it tries with img_0.jpg, checks if it is on the server and tries with img_1.jpg.
<?php
$img = "images/" . $_FILES [ 'bilde' ][ 'name' ];
$t = 0 ;
while( file_exists ( $img )) $img = "images/" . $_FILES [ 'bilde' ][ 'name' ];
$img = substr ( $img , 0 , strpos ( $img , "." )). "_ $t " . strstr ( $img , "." );
$t ++;
>
move_uploaded_file ( $_FILES [ 'bilde' ][ 'tmp_name' ], $img );
?>

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.

<?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 ;
>

If checking for a file newly created by an external program in Windows then file_exists() does not recognize it immediately. Iy seems that a short timeout may be required.

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

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

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

Замечание:

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

Замечание:

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

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

Ошибки

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

Примеры

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 30 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 ;)

Note that realpath() will return false if the file doesn't exist. So if you're going to absolutize the path and resolve symlinks anyway, you can just check the return value from realpath() instead of calling file_exists() first I needed to measure performance for a project, so I did a simple test with one million file_exists() and is_file() checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file() needed 3.0 for scenario one and 3.3 seconds for scenario two. file_exists() needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists() is faster.

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.

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

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.

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.

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

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 ;
>
?>

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.

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.

Note that this will return false for streams, eg, php://stdin.

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.

Here is a simpler version of url_exists:

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.

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!

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 ;
>
?>

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

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 ;
>
?>

file_exists will have trouble finding your file if the file permissions are not read enabled for 'other' when not owned by your php user. I thought I was having trouble with a directory name having a space in it (/users/andrew/Pictures/iPhoto Library/AlbumData.xml) but the reality was that there weren't read permissions on Pictures, iPhoto Library or AlbumData.xml. Once I fixed that, file_exists worked.

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)

Great alternative to file_exists() is stream_resolve_include_path()

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.

I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.

It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.

<?PHP
// .htaccess php_value include_path '/home/user/public_html/';

// includes lies in /home/user/public_html/includes/

//doesn't work, file_exists returns false
if ( file_exists ( 'includes/config.php' ) )
include( 'includes/config.php' );
>

//does work, file_exists returns true
if ( file_exists ( '/home/user/public_html/includes/config.php' ) )
include( 'includes/config.php' );
>
?>

Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.

The code can be used to t a filename that can be used to create a new filename.

<?php
function generateRandomString ( $length = 8 )
<
$string = "" ;

//character that can be used
$possible = "0123456789bcdfghjkmnpqrstvwxyz" ;

for( $i = 0 ; $i < $length ; $i ++)
<
$char = substr ( $possible , rand ( 0 , strlen ( $possible )- 1 ), 1 );

if (! strstr ( $string , $char ))
<
$string .= $char ;
>
>

function randomFile ( $folder = '' , $extension = '' )
<
$folder = trim ( $folder );
$folder = ( $folder == '' ) ? './' : $folder ;

//check if directory exist
if (! is_dir ( $folder ))

//generate a filepath
$filepath = $folder . "/" . generateRandomString ( 128 ) . $extension ;

//check if that filepath already exist, if it exist if generates again
//till if gets one that doesn't exist
while( file_exists ( $filepath ))
<
$filepath = $folder . "/" . generateRandomString ( 128 ) . $extension ;
>

My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):

<?php
function __autoload ( $name )
<
$path = explode ( ":" , ini_get ( 'include_path' )); //get all the possible paths to the file (preloaded with the file structure of the project)
foreach( $path as $tryThis )
<
//try each possible iteration of the file name and use the first one that comes up
// name.class.php first
$exists = file_exists ( $tryThis . '/' . $name . '.class.php' );
if ( $exists )
<
include_once( $name . '.class.php' );
return;
>

//ok that didn't work, try the other way around
$exists = file_exists ( $tryThis . '/' . 'class.' . $name . '.php' );
if ( $exists )
<
include_once( 'class.' . $name . '.php' );
return;
>

//neither did that. let's try as an inc.php
$exists = file_exists ( $tryThis . '/' . $name . '.inc.php' );
if ( $exists )
<
include_once( $name . '.inc.php' );
return;
>
>


// can't find it.
die( "Class $name could not be found!" );
>
?>

The following script checks if there is a file with the same name and adds _n to the end of the file name, where n increases. if img.jpg is on the server, it tries with img_0.jpg, checks if it is on the server and tries with img_1.jpg.
<?php
$img = "images/" . $_FILES [ 'bilde' ][ 'name' ];
$t = 0 ;
while( file_exists ( $img )) $img = "images/" . $_FILES [ 'bilde' ][ 'name' ];
$img = substr ( $img , 0 , strpos ( $img , "." )). "_ $t " . strstr ( $img , "." );
$t ++;
>
move_uploaded_file ( $_FILES [ 'bilde' ][ 'tmp_name' ], $img );
?>

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.

<?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 ;
>

If checking for a file newly created by an external program in Windows then file_exists() does not recognize it immediately. Iy seems that a short timeout may be required.

string $filename - внутри функции: string -строка, $filename - имя файла(условно).

: bool - возвращаемые значения-тип булев(true или false)(да, нет)

Адрес файла($filename) для функции is_file

Есть несколько вариантов передавать $filename в функцию is_file:

Это может быть название файла без папок. Работает с условиями, в двух словах не объяснишь, поэтому см. здесь

И второй вариант это путь на сервере

Как использовать функцию is_file

С теорией покончили. перейдем к полевым испытаниям и разберемся, как использовать функцию is_file!

Для того, чтобы протестировать функцию "is_file" испытаем на двух файлах. который существует и который не существует!

Проверяем файл, который существует функцией is_file

Выведем путь с помощью __FILE__(т.е. мы возьмем(для примера) файл данной страницы)

$example_path = "home/domen/dwweb_ru/www/is_file_funktsiya.html"

Напишем условие(и добавим var_dump):

if(is_file($example_path))
<
echo "файл существует.";
echo "<br>"
var_dump(is_file($example_path));
>
else
<
echo "файл НЕ существует.";
echo "<br>"
var_dump(is_file($example_path));
>

И разместим выше приведенный код прямо здесь:

Результат проверки файла, который существует с помощью функции is_file

Проверяем файл, который НЕ существует функцией is_file

Нам понадобится путь до файла. который не существует:

Выше приведенные условия применим к файлу

Результат проверки файла, который НЕ существует с помощью функции is_file

is_file против file_exists

Сравним эти две функции.

Опять же. не буду разводить теории, проверим на двух функциях их отношение к

Как вы наверное поняли. первая - это файл, а вторая это папка.

1). Применим file_exists к __FILE__:

echo "файл существует.";

echo "файл НЕ существует.";

2). Применим file_exists к __DIR__ :

echo "файл существует.";

echo "файл НЕ существует.";

3). Применим is_file к __FILE__ :

echo "файл существует.";

echo "файл НЕ существует.";

4). Применим is_file к __DIR__:

echo "файл существует.";

echo "файл НЕ существует.";

файл НЕ существует.

Какая разница между is_file и file_exists?

file_exists на __DIR__ возвращает true. Т.е для "file_exists", что папка, что файл. одинаково.

Не локальный путь filename функции is_file

Хотел объяснить в двух словах. не получается.

Итак. если вы собираетесь использовать лишь название файла, то такой вариант будет срабатывать, если у вас не единая точка входа.

Если у вас на сайте единая точка входа

Чтобы долго не рассказывать теорию. рассмотрим эту ситуацию на примере.

Предположим , что у нас есть папка(folder_2).

В папке folder_2 находится файл "tekst.txt"

В этой же папке находится файл "example.php" с функцией is_file и если мы создадим вот такую конструкцию :

То возникнет ошибка уровня "E_WARNING", и var_dump вернет "bool(false)":

Если у вас на сайте единая точка входа

Если у вас на сайте единая точка входа

Читайте также: