php проверить существование папки
file_exists
(PHP 4, PHP 5, PHP 7, PHP 8)
file_exists — Проверяет существование указанного файла или каталога
Описание
Проверяет наличие указанного файла или каталога.
Список параметров
Путь к файлу или каталогу.
Возвращаемые значения
Данная функция возвращает false для символических ссылок, указывающих на несуществующие файлы.
Проверка происходит с помощью реальных UID/GID, а не эффективных идентификаторов.
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Ошибки
Примеры
Пример #1 Проверка существования файла
Примечания
Смотрите также
User Contributed Notes 30 notes
Note: The results of this function are cached. See clearstatcache() for more details.
file_exists() does NOT search the php include_path for your file, so don’t use it before trying to include or require.
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..
$file = ‘http://www.domain.com/somefile.jpg’;
$file_headers = @get_headers($file);
if($file_headers[0] == ‘HTTP/1.1 404 Not Found’) <
$exists = false;
>
else <
$exists = true;
>
If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:
You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on «Open a session as» Create a new user that has enough permissions and also be sure that target share has the proper permissions.
Hope this save some hours of research to anyone.
With PHP 7.0 on Ubuntu 17.04 and with the option allow_url_fopen=On, file_exists() returns always false when trying to check a remote file via HTTP.
returns always «missing», even for an existing URL.
I found that in the same situation the file() function can read the remote file, so I changed my routine in
This is clearly a bit slower, especially if the remote file is big, but it solves this little problem.
For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.
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.
Note on openspecies entry (excellent btw, thanks!).
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.
this code here is in case you want to check if a file exists in another server:
Here is a simpler version of url_exists:
When using file_exists, seems you cannot do:
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:
I made a bit of code that sees whether a file served via RTSP is there or not:
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.
Older php (v4.x) do not work with get_headers() function. So I made this one and working.
file_exists() will return FALSE for broken links
You could use document root to be on the safer side because the function does not take relative paths:
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.
// 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’ );
>
The code can be used to t a filename that can be used to create a new filename.
//character that can be used
$possible = «0123456789bcdfghjkmnpqrstvwxyz» ;
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):
file_exists() is vulnerable to race conditions and clearstatcache() is not adequate to avoid it.
The following function is a good solution:
IMPORTANT: The file will remain on the disk if it was successfully created and you must clean up after you, f.ex. remove it or overwrite it. This step is purposely omitted from the function as to let scripts do calculations all the while being sure the file won’t be «seized» by another process.
NOTE: This method fails if the above function is not used for checking in all other scripts/processes as it doesn’t actually lock the file.
FIX: You could flock() the file to prevent that (although all other scripts similarly must check it with flock() then, see https://www.php.net/manual/en/function.flock.php). Be sure to unlock and fclose() the file AFTER you’re done with it, and not within the above function:
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.
500000) break; // wait a moment
>
if (file_exists($file)) // now should be reliable
?>
property_exists
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
property_exists — Проверяет, содержит ли объект или класс указанный атрибут
Описание
Функция проверяет, существует ли атрибут property в указанном классе.
Список параметров
Имя класса или объект класса для проверки
Возвращаемые значения
Примеры
Пример #1 Пример использования property_exists()
Примечания
Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс ещё не известен.
Смотрите также
User Contributed Notes 10 notes
The function behaves differently depending on whether the property has been present in the class declaration, or has been added dynamically, if the variable has been unset()
$testObject = new TestClass ;
If you want to test if declared *public* property was unset, you can use the following code:
As of PHP 5.3.0, calling property_exists from a parent class sees private properties in sub-classes.
declared properties cannot be unset
any set property does exist, even being set to null, regardless how it was set
[before-constructed] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(false)
[my_constructed_null]: bool(false)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)
[after-constructed] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)
[before-assigned] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)
[after-assigned] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(true)
[my_assigned_null]: bool(true)
[after-unset] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(false)
[my_constructed_null]: bool(false)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)
Как проверить существование файла на PHP?
Бывают случаи, когда вам необходимо проверить, существует ли указанный файл или нет, например, для того чтобы в последующем совершить с файлом какие-то действия.
Я тоже при разработке модуля столкнулся с этим вопросом. И нашел два варианта решения поставленной задачи.
Проверка существования файла по URL-ссылке
В PHP существует функция «fopen», с помощью которой можно открыть указанный URL.
Что мы делаем? Пытаемся открыть файл, и если нам это удается, значит, файл существует, а противном же случае – файла нет.
А что, если мы имеем не один файл, а несколько, так сказать, массив ссылок? Эта задача как раз и стояла изначально передо мной. И решение уже такой задачи следующее:
В этом случае мы получаем список только тех файлов, которые существуют.
Проверка существования локального файла
Под словом «локальный» подразумевается, что скрипт и файлы для проверки находятся на одном сервере. Если у вас довольно большой массив ссылок – этот вариант самый лучший для решения задачи, так как мы делаем не запрос на сторонний сервер, а сканирование указанных директорий.
В этом способе используется функция «file_exists», и по аналогии с предыдущим вариантом просто заменяется часть скрипта:
И то же самое для массива ссылок:
На что стоит обратить внимание? На то, что этот способ удобен для прогонки файлов, находящихся в пределах нашей файловой системы. Поэтому все ссылки желательно указывать относительные.
Кстати говоря, делая один из заказов, именно этим способом мне удалось просканировать порядка 135 000 файлов всего за пару секунд.
Существует файл в php примеры
Все способы проверки существования файла
Что такое file_exists
Синтаксис функции file_exists
Давайте попробуем разобрать синтаксис функции file_exists
Как проще написать функцию file_exists
Как переводится file_exists.
File already exists перевод
Что возвращает file_exists
Как получить возвращаемые значения относительно файла в file_exists
Применим её к file_exists таким образом:
$file = «/index.html»; //главная страница сайта
Результат возврата функции file_exists к существующему файлу
Тоже самое проделаем с файлом, который не существует! Внутри неважно что мы напишем, должно быть единственное условие, что файла не существует:
Результат возврата функции file_exists к не существующему файлу
Всего три варианта проверки file_exists
Вообще существует, как минимум 3 варианта написания пути к файлу, это:
Локально(поскольку данным вариантом пути я никогда не пользуюсь, то и смыслы писать о нём нет).
Далее. в подробностях рассмотрим эти три варианта!
Существует ли файл в папке проверка локально file_exists
Предположим, что файл со скриптом и проверяемый файл лежат в одной папке, тогда можно проверить существует ли файл локально таким образом:
Если у вас на сайте единая точка входа, и оба файла подчинены этому, то file_exists вернет «true» хотя должен вернуть «false»(при отсутствующем файле. )
Нужен пример!? легко!
Если мы сейчас посмотрим в адресную строку, то мы увидим вот это:
Давайте выведем этот код прямо здесь:
— Парадокс!? Нет! Объясняется просто!
Чтобы вы понимали, именно проверять таким образом локально, в приведенном примере, корневая папка, будет той локальной папкой для этой проверки существования файла!
Все файлы, например sitemap.xml, которые будут физически находиться в корневой папке сайта, file_exists будет возвращать true!
Проделаем тоже относительно нашего файла, на котором данный текст
И второй файл. на котором расположим точно такую же запись, кроме названия самого файла.
Два идентичных кода с использованием функции file_exists.
Расположенных на файлах отличающихся правилом обработки единая точка входа
Будут давать противоположные ответы.
Проверка существования файла по абсолютному пути file_exists
Проверка существования файла по пути на сервере file_exists
Теперь возьмем тоже самый существующий файл и применим уже не абсолютный путь, а путь на сервере до файла и вставим его в в функцию file_exists
И получим результат работы функции file_exists :
Вывод о существовании файла и функции file_exists
Какой вывод можно сделать по тем проверкам существования или отсутствия файла на сервере!?
is_file
(PHP 4, PHP 5, PHP 7, PHP 8)
is_file — Определяет, является ли файл обычным файлом
Описание
Определяет, является ли файл обычным файлом.
Список параметров
Возвращаемые значения
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Ошибки
Примеры
Пример #1 Пример использования is_file()
Результат выполнения данного примера:
Примечания
Смотрите также
User Contributed Notes 23 notes
### Symbolic links are resolved ###
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.
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,
here is a workaround for the file size limit. uses bash file testing operator, so it may be changed to test directories etc. (see http://tldp.org/LDP/abs/html/fto.html for possible test operators)
regarding note from rehfeld dot us :
In my experience the best( and easiest ) way to find the extension of a file is :
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.
you should replace a string between » with your file path to check
be careful, is_file() fails on files larger than your integer storage (2^32 for most).
This Function deletes everything in a defined Folder:
Works with PHP 4 and 5.
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
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:
BTW, each successive call to dirname takes you one step up in the directory tree.
echo __FILE__ ;
// /www/site.com/public/index.php
echo dirname ( __FILE__ );
// /www/site.com/public
echo dirname ( dirname ( __FILE__ ));
// /www/site.com
?>
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 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:
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.
regarding rlh at d8acom dot com method,
It is incorrect. Well, it works but you are not guaranteed the file extension using that method.
for example : filename.inc.php
your method will tell you the ext is «inc», but it is in fact «php»