Проверить пустой ли файл php
Поскольку PHP является серверным языком программирования, он позволяет вам работать с файлами и каталогами, хранящимися на веб-сервере. В этом руководстве вы узнаете, как создавать, получать доступ и управлять файлами на вашем веб-сервере с помощью функций файловой системы PHP.
Функции файловой системы PHP
В следующей таблице представлен обзор некоторых других полезных функций файловой системы PHP, которые можно использовать для динамического чтения и записи файлов.
Функция | Описание |
---|---|
fgetc() | Читает по одному символу за раз. |
fgets() | Читает по одной строке за раз. |
fgetcsv() | Читает строку значений, разделенных запятыми. |
filetype() | Возвращает тип файла. |
feof() | Проверяет, достигнут ли конец файла. |
is_file() | Проверяет, является ли файл обычным файлом. |
is_dir() | Проверяет, является ли файл каталогом. |
is_executable() | Проверяет, является ли файл исполняемым. |
realpath() | Возвращает канонизированный абсолютный путь. |
rmdir() | Удаляет пустой каталог. |
Пожалуйста, ознакомьтесь со справочником по файловой системе PHP, чтобы узнать о других полезных функциях файловой системы PHP.
Насколько публикация полезна?
Нажмите на звезду, чтобы оценить!
Средняя оценка 5 / 5. Количество оценок: 1
Оценок пока нет. Поставьте оценку первым.
Смотрите также
- is_dir() - Определяет, является ли имя файла директорией
- is_link() - Определяет, является ли файл символической ссылкой
- SplFileInfo
Закрытие файла с помощью PHP-функции fclose()
Закончив работу с файлом, его нужно закрыть. Функция fclose() используется для закрытия файла, как показано в следующем примере:
Хотя PHP автоматически закрывает все открытые файлы при завершении скрипта, рекомендуется закрывать файл после выполнения всех операций.
Примечания
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Открытие файла с помощью PHP-функции fopen()
Для работы с файлом вам сначала нужно открыть файл. Функция PHP fopen() используется для открытия файла. Базовый синтаксис этой функции может быть задан следующим образом:
Первый параметр, передаваемый в fopen() , указывает имя файла, который вы хотите открыть, а второй параметр указывает, в каком режиме файл должен быть открыт. Например:
Файл можно открыть в одном из следующих режимов:
Режим | Что он делает |
---|---|
r | Открывает файл только для чтения. |
r+ | Открывает файл для чтения и записи. |
w | Открывает файл только для записи и очищает содержимое файла. Если файл не существует, PHP попытается его создать. |
w+ | Открывает файл для чтения, записи и очищает содержимое файла. Если файл не существует, PHP попытается его создать. |
a | Открывает файл только для записи. Сохраняет содержимое файла, записывая его в конец. Если файл не существует, PHP попытается его создать. |
a+ | Открывает файл для чтения и записи. Сохраняет содержимое файла, записывая его в конец. Если файл не существует, PHP попытается его создать. |
x | Открывает файл только для записи. Возвращает FALSE и выдает ошибку, если файл уже существует. Если файл не существует, PHP попытается его создать. |
x+ | Открывает файл для чтения и записи; в противном случае он ведет себя так же, как ‘x’. |
Операции с файлами и каталогами подвержены ошибкам. Поэтому рекомендуется реализовать некоторую форму проверки ошибок, чтобы в случае возникновения ошибки ваш скрипт корректно ее обработал. См. Руководство по обработке ошибок в PHP.
Errors/Exceptions
Upon failure, an E_WARNING is emitted.
Руководство по загрузке файлов на сервер в PHP
В этом руководстве мы узнаем, как загружать файлы на удаленный сервер с помощью простой HTML-формы и PHP. Вы можете загружать файлы любого типа, например изображения, видео, ZIP-файлы, документы Microsoft Office, PDF-файлы, а также исполняемые файлы и множество других типов файлов. Шаг 1. Создание HTML-формы для загрузки файла В следующем примере будет создана простая HTML-форма, которую…
Примечания
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
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 ;
>
На платформах Windows, для проверки наличия файлов на сетевых ресурсах, используйте имена, подобные //computername/share/filename или \\computername\share\filename .
Чтение файла: file()
Функция file() позволяет получить содержимое файла в виде массива. Разделителем элементов является символ переноса строки.
Создадим в корне сайта файл data.txt со следующим содержимым:
Теперь запустим скрипт index.php со следующим кодом:
При запуске этого скрипта мы получим в браузере:
Заметили, что у первых двух строк длина 7 символов вместо пяти? Это из-за того, что каждая строка содержит в конце символы переноса строки.
Чаще всего они нам не нужны, поэтому их можно убрать, передав вторым параметром константу FILE_IGNORE_NEW_LINES :
Теперь у всех строк будет по 5 символов.
Если нам необходимо получить только заполненные строки в файле и пропустить пустые, можно передать вторым параметром константу FILE_SKIP_EMPTY_LINES :
Разумеется, мы можем передать сразу две константы:
Переименование файлов с помощью PHP-функции rename()
Вы можете переименовать файл или каталог с помощью PHP-функции rename() , например:
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Похожие посты
Запись файлов с помощью PHP-функции fwrite()
Точно так же вы можете записывать или добавлять данные в существующий файл с помощью PHP-функции fwrite() . Базовый синтаксис этой функции может быть задан следующим образом:
Функция fwrite() принимает два параметра — дескриптор файла и строку данных, которые должны быть записаны, как показано в следующем примере:
В приведенном выше примере, если файл note.txt не существует, PHP автоматически создаст его и запишет данные. Но если файл note.txt уже существует, PHP удалит содержимое этого файла, если оно есть, перед записью новых данных, однако, если вы просто хотите добавить файл и сохранить существующее содержимое, просто используйте режим a вместо w в приведенном выше примере.
Альтернативный способ — использовать функцию file_put_contents() . Это аналог функции file_get_contents() и простой метод записи данных в файл без необходимости его открытия. Эта функция принимает имя и путь к файлу вместе с данными, которые будут записаны в файл. Вот пример:
Если файл, указанный в функции file_put_contents() , уже существует, PHP по умолчанию перезапишет его. Если вы хотите сохранить содержимое файла, вы можете передать специальный флаг FILE_APPEND в качестве третьего параметра функции file_put_contents() . Он просто добавит новые данные в файл вместо того, чтобы перезаписывать его. Вот пример:
Чтение всего содержимого файла
Функцию fread() можно использовать вместе с функцией filesize() для одновременного чтения всего файла. Функция filesize() возвращает размер файла в байтах.
Самый простой способ прочитать все содержимое файла в PHP — использовать функцию readfile() . Эта функция позволяет вам читать содержимое файла, не открывая его. В следующем примере будет сгенерирован тот же результат, что и в примере выше:
Другой способ прочитать все содержимое файла без необходимости его открытия — использовать функцию file_get_contents() . Эта функция принимает имя и путь к файлу и считывает весь файл в строковую переменную. Вот пример:
Еще один метод чтения всех данных из файла — это PHP-функция file() . Она выполняет ту же работу, что и функция file_get_contents() , но возвращает содержимое файла в виде массива строк, а не отдельной строки. Каждый элемент возвращаемого массива соответствует строке в файле.
Для обработки данных файла необходимо выполнить итерацию по массиву с помощью цикла foreach. Вот пример, который считывает файл в массив, а затем отображает его с помощью цикла:
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.
On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.
Проверка существования файла или папки
Проверить существование папки или файла можно с помощью функции file_exists() :
Если вы хотите проверить существование только папки или только файла, для этого есть специальные функции is_dir() и is_file() :
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.
Чтение фиксированного количества символов
Функцию fread() можно использовать для чтения указанного количества символов из файла. Базовый синтаксис этой функции можно задать с помощью.
Эта функция принимает два параметра — дескриптор файла и количество байтов для чтения. В следующем примере из файла data.txt считывается 20 байтов, включая пробелы. Предположим, файл data.txt содержит абзац текста «The quick brown fox jumps over the lazy dog.»
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.
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 ;
>
С помощью функции file_get_contents() можно получить содержимое файла:
Также мы можем получить html-код какой-либо страницы в интернете:
Но работает это далеко не для всех сайтов, у многих есть защита от такого примитивного парсинга.
Создание папки или структуры папок
Создать папку можно с помощью функции mkdir() (make directory):
Вторым параметром указываются права доступа к файлу в виде восьмеричного числа, по-умолчанию это 0777 , что означает самые широкие права. Для Windows этот аргумент игнорируется.
Кроме этого, второй параметр может игнорироваться при заданной umask (пользовательская маска (user mask), которая нужна для определения конечных прав доступа). В этом случае принудительно сменить права можно функцией chmod() :
Также мы можем создать структуру папок рекурсивно, для этого нужно третьим параметром передать true :
Но в этом случае права доступа будут заданы только для конечной папки. Для изменения прав у каждой из папок придётся указывать права вручную:
Права доступа - это отдельная объёмная тема, поэтому сейчас мы её пока рассматривать не будем.
Примеры
if ( file_exists ( $filename )) echo "Файл $filename существует" ;
> else echo "Файл $filename не существует" ;
>
?>
Примеры
Результат выполнения данного примера:
Создание файла и запись в файл: file_put_contents()
Функция file_put_contents() позволяет создать файл и заполнить его данными.
Первым параметром функция принимает путь к файлу, вторым - строку с данными. Для создания пустого файла нужно передать вторым параметром пустую строку.
Если файла не существует - он будет создан. Если существует - данные в файле будут перезаписаны.
Чтобы не перезаписывать данные, а добавить их в конец файла, нужно передать третьим параметром константу FILE_APPEND :
Также вторым параметром можно передать массив:
Но этот вариант не очень удобен, поскольку все элементы массива запишутся подряд, без каких-либо разделителей. Чтобы их добавить, можно использовать функцию implode:
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
Чтение файлов с помощью PHP-функции fread()
Теперь, когда вы поняли, как открывать и закрывать файлы. В следующем разделе вы узнаете, как читать данные из файла. В PHP есть несколько функций для чтения данных из файла. Вы можете прочитать от одного символа до всего файла с помощью одной операции.
Examples
if ( file_exists ( $filename )) echo "The file $filename exists" ;
> else echo "The file $filename does not exist" ;
>
?>
Удаление файлов с помощью PHP-функции unlink()
Вы можете удалять файлы или каталоги с помощью PHP-функции unlink() , например:
В следующей главе мы узнаем больше о разборе каталогов или папок в PHP.
Руководство по GET и POST запросам в PHP
Разработка сайтов для бизнеса
Если у вас есть вопрос, на который вы не знаете ответ — напишите нам, мы поможем разобраться. Мы всегда рады интересным знакомствам и новым проектам.
Возвращает true , если файл существует и является обычным файлом, иначе возвращает false .
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Возвращаемые значения
Возвращает true , если файл или каталог, указанный параметром filename , существует, иначе возвращает false .
Замечание:
Данная функция возвращает false для символических ссылок, указывающих на несуществующие файлы.
Замечание:
Проверка происходит с помощью реальных UID/GID, а не эффективных идентификаторов.
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Работа с файлами с помощью fopen()
Функций file() , file_get_contents() и file_put_contents() достаточно для решения большинства задач, связанных с управлением файлами.
Но иногда возникают ситуации, когда нам необходимы более продвинутые инструменты. Например, если у нас есть большой текстовый файл и мы хотим читать его построчно, а не весь сразу, для экономии оперативной памяти.
Итак, открыть (или создать и открыть) файл можно с помощью функции fopen() :
Функция fopen() возвращает так называемый лескриптор. Это ссылка, указатель на файл, его мы будем передавать в другие функции. Кстати, тип данных этого дескриптора - resource .
Первым параметром мы передаём путь к файлу, вторым - модификатор доступа к файлу. Ниже перечислены наиболее популярные модификаторы:
- r - открытие для чтения, указатель переходит в начало файла.
- r+ - открытие для чтения и записи, указатель переходит в начало файла.
- w - открытие для записи, указатель переходит в начало файла. Если файла нет - создаётся, если есть - очищается от данных.
- w+ - открытие для чтения и записи, в остальном аналогичен w .
- a - открытие для записи, указатель переходит в конец файла. Если файла нет - создаётся.
- a+ - открытие для чтения и записи, в остальном аналогичен a .
- x - создание и открытие для записи, указатель переходит в начало файла. Если файл существует - PHP покажет ошибку.
- x+ - создание и открытие для чтения и записи, в остальном аналогичен x .
Указатель - это нечто вроде курсора. Вы можете переместить его в любое место файла, чтобы добавить или отредактировать определённые данные.
Для записи данных в файл существует функция fwrite() . Давайте попробуем создать файл и записать в него какие-нибудь данные:
Заметьте, из-за модификатора w при каждом запуске скрипта данные в файле стираются и добавляются заново. Если модификатор заменить на a , данные будут не перезаписываться, а добавляться в конец файла.
Для построчного чтения файла используется функция fgets() :
При каждом запуске fgets получает следующую строку и возвращает её в $line . Вторым параметром передаётся максимальная длина строки. Это означает, что если строка слишком длинная, она будет обрезана.
Также в PHP существует множество других полезных функций, работающих с дескриптором файла. Почитать о них можно в документации.
Копирование, перенос и удаление файла
Для удаления файлов используется функция unlink() :
Чтобы скопировать файл, используем функцию copy() :
Для переименования и переноса файла в другую папку используется функция rename() :
Смотрите также
- is_readable() - Определяет существование файла и доступен ли он для чтения
- is_writable() - Определяет, доступен ли файл для записи
- is_file() - Определяет, является ли файл обычным файлом
- file() - Читает содержимое файла и помещает его в массив
- SplFileInfo
Проверка прав доступа
Функции is_readable() и is_writable() проверяют, есть ли у пользователя, от имени которого запущен PHP, права на чтение и запись файла или папки:
Читайте также: