Php file exists не видит файл
Возвращает true , если файл существует и является обычным файлом, иначе возвращает false .
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Примеры
if ( file_exists ( $filename )) echo "Файл $filename существует" ;
> else echo "Файл $filename не существует" ;
>
?>
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.
Смотрите также
- is_dir() - Определяет, является ли имя файла директорией
- is_link() - Определяет, является ли файл символической ссылкой
- SplFileInfo
User Contributed Notes 23 notes
Note that is_file() returns false if the parent directory doesn't have +x set for you; this make sense, but other functions such as readdir() don't seem to have this limitation. The end result is that you can loop through a directory's files but is_file() will always fail.
If you pass a symlink (unix symbolic link) as parameter, is_file will resolve the symlink and will give information about the refered file. For example:
is_dir resolves symlinks too.
if you're running apache as a service on a win32 machine, an you try to determinate if a file on an other pc in your network exists - ex.: is_file('//servername/share/dir1/dir2/file.txt') - you may return false when you're running the service as LocalSystem. To avoid this, you have to start the Apache-Service as a 'registered' domain user.
I tend to use alot of includes, and I found that the is_file is based on the script executed, not ran.
if you request /foo.php and foo.php looks like this:
include( 'foobar/bar.php' );
?>
and bar.php looks like this:
echo ( is_file ( 'foo/bar.txt' ));
?>
Then PHP (on win32, php 5.x) would look for /foo/bar.txt and not /foobar/foo/bar.txt.
you would have to rewrite the is_file statement for that, or change working directory.
Noting this since I sat with the problem for some time,
function is_file_lfs ( $path ) exec ( '[ -f "' . $path . '" ]' , $tmp , $ret );
return $ret == 0 ;
>
?>
regarding note from rehfeld dot us :
In my experience the best( and easiest ) way to find the extension of a file is :
// use this when you are sure it actually has an extension.
$extension = end ( explode ( "." , $file_name ));
// this one will also check if it actually has an extension
$parts = explode ( "." , $file_name );
if ( is_array ( $parts ) && count ( $parts ) > 1 )
$extension = end ( $parts );
In PHP 4.1.0 under win32, this seems to print out a warning message if the file does not exist (using error_reporting = E_ALL & ~E_NOTICE).
is_file doesn't recognize files whose filenames contain strange characters like czech ů or russian characters in general.
I've seen many scripts that take it for granted that a path is a directory when it fails is_file($path). When trying to determine whether a path links to a file or a dir, you should always use is_dir after getting false from is_file($path). For cases like described above, both will fail.
sometimes this function does not work because permission ,
you can use this function that check if the path has dot in last will return true .
public function isFile($file) $f = pathinfo($file, PATHINFO_EXTENSION);
return (strlen($f) > 0) ? true : false;
>
you should replace a string between '' with your file path to check
It took me a day or so to figure out that is_file() actually looks for a valid $ existing path/file in string form. It is not performing a pattern-like test on the parameter given. Its testing to see if the given parameter leads to a specific existing 'name.ext' or other (non-directory) file type object.
Maybe this is a newbie mistake, but note that paths are relative to the filesystem and the location of the script. This means that MS IIS virtual directories are not available by relative path - use an absolute.
This threw me because virtual directories ARE available for URLs, at least on IIS.
be careful, is_file() fails on files larger than your integer storage (2^32 for most).
Warning: is_file(): Stat failed for bigfile (errno=75 - Value too large for defined data type)
This Function deletes everything in a defined Folder:
Works with PHP 4 and 5.
function deletefolder ( $path )
<
if ( $handle = opendir ( $path ))
<
while ( false !==( $file = readdir ( $handle )))
<
if ( $file <> "." AND $file <> ".." )
<
if ( is_file ( $path . '/' . $file ))
<
@ unlink ( $path . '/' . $file );
>
if ( is_dir ( $path . '/' . $file ))
<
deletefolder ( $path . '/' . $file );
@ rmdir ( $path . '/' . $file );
>
>
>
>
>
?>
I have noticed that using is_file on windows servers (mainly for development) to use a full path c:\ doesn't always work.
I have had to use
C:/foldertowww/site/file.ext
so I preform an str_replace('\\', '/', $path)
Sometimes I have had the \ instead of / work. (this is using apache2 on XP)
but for sure you cannot have mixed separators.
An easy way not to have to choose between hard-coding full paths and using relative paths is either via this line:
// in the bootstrap file
define ( 'DIR_ROOT' , dirname ( __FILE__ ));
// in other files, prefix paths with the constant
require( DIR_ROOT . '/relative/to/bootstrap.php' );
?>
or if you have to use a relative path:
require( dirname ( __FILE__ ) . '/relative/to/this_file.php' );
?>
This way all your paths will be absolute, yet you can move the application anywhere in the filesystem.
BTW, each successive call to dirname takes you one step up in the directory tree.
In 32 bit environments, these functions including is_file(), stat() filesize() will not work due to PHPs default integer being signed. So anything above ~2.1 billion bytes you actually get a negative value.
This is actually a bug but I dont think there is an easy workaround. Try to switch to 64 bit.
this is a simple way to find specific files instead of using is_file().
this example is made for mac standards, but easily changed for pc.
function isfile ( $file ) <
return preg_match ( '/^[^.^:^?^\-][^:^?]*\.(?i)' . getexts () . '$/' , $file );
//first character cannot be . : ? - subsequent characters can't be a : ?
//then a . character and must end with one of your extentions
//getexts() can be replaced with your extentions pattern
>
function getexts () <
//list acceptable file extensions here
return '(app|avi|doc|docx|exe|ico|mid|midi|mov|mp3|
mpg|mpeg|pdf|psd|qt|ra|ram|rm|rtf|txt|wav|word|xls)' ;
>
echo isfile ( '/Users/YourUserName/Sites/index.html' );
?>
I see, is_file not work properly on specifical file in /dev (linux)
look :
I do a lot of file parsing and have found the following technique extremely useful:
while (false !== ($document = readdir($my_dir)))
$ext=explode('.',$document);
if($document != '.' && $document != '..' && $ext[1])
'Do something to file. '
>
>
It gets around the fact that, when working on website pages, the html files are read as directories when downloaded. It also allows you to extend the usefulness of the above method by adding the ability to determine file types e.g.
if($document != '.' && $document != '..' && $ext[1]=='htm')
or
if($document != '.' && $document != '..' && $ext[1]=='doc')
regarding rlh at d8acom dot com method,
It is incorrect. Well, it works but you are not guaranteed the file extension using that method.
Добра вам "коллеги".
Столкнулся я сегодня с неведомой ранее фигнёй.
Пишу код всё работает. и вдруг перестаёт.
Имеется переменная dom
при этом:
делаю var_dump и получаю : string(61) "/home/users2/k/kkk/domains/my.domen.ru/file/idnex.php"
а если сделать var_export то получаю: '/home/users2/k/kkk/domains/my.domen.ru/file/' . "\0" . 'index.php'
Кто нибудь имеет информацию откуда появляется
и почему ваще перестало file_exist() срабатывать?
Код сильно утрирован что бы не перегружать ваши мозги
File_exists Не видит файл в каталоге home
Не видит файл в каталоге home. if(file_exists('/home/file.php')) require_once('/home/file.php'); .
Ошибка в пути к файлу БД
База данных аксесса лежит в одной папке с самой программой, но при перемещение этой папки в другое.
Ошибка в пути к файлу
Блин второй день сижу и не могу никак понять почему пишет вот эту ошибку: Warning: include() .
Решение
Посмотреть бы. Скорее всего отсюда берется этот \0. Потому что левый символ кроется в index, а он получается из place.
Добавлено через 4 минуты
Не совсем понял заметили Вы или нет, но там idnex вместо index. Получается это скорее из-за какого то левого символа, который не является буквой, цифрой, знаком препинания.
ошибка синтаксиса. Используйте ide а не блокнот. Тогда станет ясно что не 'file' = 'file'. DS , а 'file' => 'file'. DS
pav1uxa, idnex - опечатка, когда писал пример.
root, я использую IDE(PhpStorm) 'file' = 'file' так же опечатка, когда писал пример.
and_y87,
вот веришь как то тяжело пишешь
если массив это [] значит нахрена DS
далее в Joomla хренова куча именованных констант с различными путями поищи в define или Google что тебе надо
Сори парни, я заработался и не замечал ошибки, но в итоге смог найти эту - казявку.
проблемой было то, что я убирал первый слэш в пути через
присвоение первому элементу строки "пустоты", типо так:
Ошибка доступа к пути/файлу
Программа открывает doc файл, меняет там текст в закладках, на тот, который укажу в TextBox и.
Как из пути к файлу, оставить только сам файл
Функция вставляет полный путь к файлу, к примеру: C:\Foto\1.jpg. А мне нужно выдернуть отсюда.
Скрипт копирования пути к файлу\папке и вставка пути в письмо Outlook
Всем доброго времени суток! Помогите, пож-та, разобраться\дописать скрипт. Есть скрипт на.
Fopen не видит файл, если в его пути содержатся русские символы
Здравствуйте! Столкнулся с очень неприятной проблемой. Моя программа получает путь к нужному.
Ошибка: "Windows не удается получить доступ к указанному устройству, пути или файлу"
Доброе время суток. При запуске VBS файла на Windows 10 выдаёт ошибку "Windows не удается получить.
I'm having a very weird issue with file_exists(). I'm using this function to check if 2 different files in the same folders do exist. I've double-checked, they BOTH do exist.
Now let's use file_exists() on these:
I don't get it - both of these files do exist. I'm running Windows, so it's not related to a case-sensitive issue. Safe Mode is off.
What might be worth mentioning though is that the .jpg one is uploaded by a user via FTP, while the .jpg one is created using a script. But as far as I know, that shouldn't make a difference.
For me it ended up being because it requires an absolute path, not a relative path. Some PHP functions accept a path relative to the current file, one being parse_ini_file.
I also thought I had this issue. After checking the spelling 10 times I realised that the filename ended in ".jpg.jpg". It's true, I am a failure
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 ;)
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.
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
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.
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.
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.
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
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.
When using file_exists, seems you cannot do:
foreach ( $possibles as $poss )
<
if ( file_exists ( SITE_RANGE_IMAGE_PATH . $this -> range_id . '/ ' . $poss . '.jpg' ) )
<
// exists
>
else
<
// not found
>
>
?>
so you must do:
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 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.
function imageExists ( $image , $dir )
$i = 1 ; $probeer = $image ;
I was having problems with the file_exists when using urls, so I made this function:
function file_exists_2 ( $filePath )
return ( $ch = curl_init ( $filePath )) ? @ curl_close ( $ch ) || true : false ;
>
?>
Cheers!
this code here is in case you want to check if a file exists in another server:
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:
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.
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
I made a bit of code that sees whether a file served via RTSP is there or not:
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.
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 ;
>
?>
You could use document root to be on the safer side because the function does not take relative paths:
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.
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.
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.
// .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.
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)
The code can be used to t a filename that can be used to create a new filename.
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 ;
>
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.
$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 );
?>
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):
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!" );
>
?>
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.
$file = 'file.tmp';
if ($h = popen("start \"bla\" touch $file", "r")) pclose($h);
// now I would like know if a file was created
// note: usleep not supported
$start = gettimeofday();
while (!file_exists(trim($file, " '\""))) $stop = gettimeofday();
if ( 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'] > 500000) break; // wait a moment
>
if (file_exists($file)) // now should be reliable
?>
file_exists() is vulnerable to race conditions and clearstatcache() is not adequate to avoid it.
The following function is a good solution:
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.
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 ;
>
Примеры
Результат выполнения данного примера:
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
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.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Возвращаемые значения
Возвращает true , если файл или каталог, указанный параметром filename , существует, иначе возвращает false .
Замечание:
Данная функция возвращает false для символических ссылок, указывающих на несуществующие файлы.
Замечание:
Проверка происходит с помощью реальных UID/GID, а не эффективных идентификаторов.
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Errors/Exceptions
Upon failure, an E_WARNING is emitted.
15 Answers 15
It only supports filesystem paths (and FTP, if you're using PHP5.)
Results of the file_exists() are cached, so try using clearstatcache() . If that not helped, recheck names - they might be similar, but not same.
This was indeed the problem. It seemed the script replaced _'s with -'s. Very hard to miss (and annoying) :|
For me clearstatcache() - didn't helped but. My class name was Multimedia. Then i used clearstatcache() - still didn't work. Then i renamed file to Multimedia2 didn't helped to. That was strange. Then I renamed file to Abc. It worked. Then renamed to Multimedia and it worked again :D It took me about half an hour.
I found that what works for me to check if a file exists (relative to the current php file it is being executed from) is this piece of code:
Just my $.02: I just had this problem and it was due to a space at the end of the file name. It's not always a path problem - although that is the first thing I check - always. I could cut and paste the file name into a shell window using the ls -l command and of course that locates the file because the command line will ignore the space where as file_exists does not. Very frustrating indeed and nearly impossible to locate were it not for StackOverflow.
HINT: When outputting debug statements enclose values with delimiters () or [] and that will show a space pretty clearly. And always remember to trim your input.
It's because of safe mode. You can turn it off or include the directory in safe_mode_include_dir . Or change file ownership / permissions for those files.
Safe mode is already turned off, so that's not the issue. Also, the permissions should be file-specific, as they're both in the same folder. I've never had these issues in Windows, but when looking at the permissions, I don't see any difference between the two.
Ah, sorry didn't see safe mode is off. If permissions are the same, you might need to check the owner id or the group id for those files, it could be that your webuser doesn't belong to the group or is not the owner of the file.
На платформах Windows, для проверки наличия файлов на сетевых ресурсах, используйте имена, подобные //computername/share/filename или \\computername\share\filename .
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
Examples
if ( file_exists ( $filename )) echo "The file $filename exists" ;
> else echo "The file $filename does not exist" ;
>
?>
Примечания
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
Примечания
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Смотрите также
- 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 ;)
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.
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
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.
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.
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.
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
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.
When using file_exists, seems you cannot do:
foreach ( $possibles as $poss )
<
if ( file_exists ( SITE_RANGE_IMAGE_PATH . $this -> range_id . '/ ' . $poss . '.jpg' ) )
<
// exists
>
else
<
// not found
>
>
?>
so you must do:
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 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.
function imageExists ( $image , $dir )
$i = 1 ; $probeer = $image ;
I was having problems with the file_exists when using urls, so I made this function:
function file_exists_2 ( $filePath )
return ( $ch = curl_init ( $filePath )) ? @ curl_close ( $ch ) || true : false ;
>
?>
Cheers!
this code here is in case you want to check if a file exists in another server:
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:
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.
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
I made a bit of code that sees whether a file served via RTSP is there or not:
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.
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 ;
>
?>
You could use document root to be on the safer side because the function does not take relative paths:
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.
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.
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.
// .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.
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)
The code can be used to t a filename that can be used to create a new filename.
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 ;
>
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.
$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 );
?>
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):
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!" );
>
?>
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.
$file = 'file.tmp';
if ($h = popen("start \"bla\" touch $file", "r")) pclose($h);
// now I would like know if a file was created
// note: usleep not supported
$start = gettimeofday();
while (!file_exists(trim($file, " '\""))) $stop = gettimeofday();
if ( 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'] > 500000) break; // wait a moment
>
if (file_exists($file)) // now should be reliable
?>
file_exists() is vulnerable to race conditions and clearstatcache() is not adequate to avoid it.
The following function is a good solution:
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.
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 ;
>
On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.
Читайте также: