проверить существование каталога php

is_dir

(PHP 4, PHP 5, PHP 7, PHP 8)

is_dir — Определяет, является ли имя файла директорией

Описание

Определяет, является ли имя файла директорией.

Список параметров

Путь к файлу. Если filename является относительным именем, он будет проверяться относительно текущей рабочей директории. Если filename является символической или жёсткой ссылкой, то ссылка будет раскрыта и проверена. При включённом open_basedir могут применяться дальнейшие ограничения.

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

Ошибки

Примеры

Пример #1 Пример использования функции is_dir()

( is_dir ( ‘a_file.txt’ ));
var_dump ( is_dir ( ‘bogus_dir/abc’ ));

var_dump ( is_dir ( ‘..’ )); // на одну директорию выше
?>

Результат выполнения данного примера:

Примечания

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

User Contributed Notes 20 notes

This is the «is_dir» function I use to solve the problems :

I can’t remember where it comes from, but it works fine.

My solution to the problem that you must include the full path to make «is_dir» work properly as a complete example:

Note that this functions follows symbolic links. It will return true if the file is actually a symlink that points to a directory.

(Windows Note: Under recent versions of Windows you can set symlinks as long as you’re administrator, but you cannot remove directory symlinks with «unlink()», you will have to use «rmdir testlink» from the shell to get rid of it.)

Running PHP 5.2.0 on Apache Windows, I had a problem (likely the same one as described by others) where is_dir returned a False for directories with certain permissions even though they were accessible.

Strangely, I was able to overcome the problem with a more complete path. For example, this only displays «Works» on subdirectories with particular permissions (in this directory about 1 out of 3):

However, this works properly for all directories:

I don’t understand the hit-and-miss of the first code, but maybe the second code can help others having this problem.

When trying (no ‘pear’) to enumerate mounted drives on a win32 platform (Win XP SP3, Apache/2.2.11, PHP/5.2.9), I used:

PITFALL in sub dir processing

After struggeling with a sub-dir processing (some subdirs were skipped) AND reading the posts, I realized that virutally no-one clearly told what were wrong.

opendir(«myphotos»); // Top dir to process from (example)

if (is_dir($fname)) call_own_subdir_process; // process this subdir by calling a routine

The «is_dir()» must have the FULL PATH or it will skip some dirs. So the above code need to INSERT THE PATH before the filename. This would give this change in above.

The pitfall really was, that without full path some subdirs were found. hope this clears all up

Note that is_dir() also works with ftp://.

if( is_dir ( ‘ftp://user:pass@host/www/path/to/your/folder’ )) <
// Your code.
>
?>

But note that if the connexion fails due to invalide credentials, this will consider that the folder doesn’t exist and will return FALSE.

Here is another way to test if a directory is empty, which I think is much simpler than those posted below:

Ah ha! Maybe this is a bug, or limitation to be more precise, of php. See http://bugs.php.net/bug.php?id=27792

A workaround is posted on the page (above) and seems to work for me:

PS: I’m using PHP 4.3.10-16, posts report this problem up to 5.0

use this function to get all files inside a directory (including subdirectories)

Note that there quite a few articles on the net that imply that commands like is_dir, opendir, readdir cannot read paths with spaces.

On a linux box, THAT is not an issue.

$dir = «Images/Soma ALbum Name with spaces»;

this function bypasses open_basedir restrictions.

example:

output:
Warning: open_basedir restriction in effect

output:
true (or false, depending whether it is or not. )


visit puremango.co.uk for other such wonders

An even better (PHP 5 only) alternative to «Davy Defaud’s function»:

When I run a scandir I always run a simple filter to account for file system artifacts (especially from a simple ftp folder drop) and the «.» «..» that shows up in every directory:

If you are using Mac, or others systems that store information about the directory layout and etc, the function:

function empty_dir($dir) <
if (($files = @scandir($dir)) && count($files)

Unfortunately, the function posted by p dot marzec at bold-sg dot pl does not work.
The corrected version is:

// returns true if folder is empty or not existing
// false if folde is full

function is_empty_folder($dir) <
if (is_dir($dir)) <
$dl=opendir($dir);
if ($dl) <
while($name = readdir($dl)) <
if (!is_dir(«$dir/$name»)) < //

Источник

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

Источник

Php проверка существования директории

проверить существование каталога php. Смотреть фото проверить существование каталога php. Смотреть картинку проверить существование каталога php. Картинка про проверить существование каталога php. Фото проверить существование каталога php

Проверяем, существует директория или нет? Если такой директории нет, создает ее.

Функция is_dir(), позволяет узнать, является ли имя файла директорией. Если такой директории нет, то создаем новую с помощью функции mkdir().

Функция file_exist(), проверяем существование указанного файла или каталога. Если такой директории нет, то создаем новую с помощью функции mkdir().

file_exists — Проверяет наличие указанного файла или каталога

Описание

Проверяет наличие указанного файла или каталога.

Список параметров

Путь к файлу или каталогу.

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

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

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

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

Примеры

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

Ошибки

Примечания

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

Бывают случаи, когда вам необходимо проверить, существует ли указанный файл или нет, например, для того чтобы в последующем совершить с файлом какие-то действия.

Я тоже при разработке модуля столкнулся с этим вопросом. И нашел два варианта решения поставленной задачи.

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

В PHP существует функция «fopen», с помощью которой можно открыть указанный URL.

Что мы делаем? Пытаемся открыть файл, и если нам это удается, значит, файл существует, а противном же случае – файла нет.

А что, если мы имеем не один файл, а несколько, так сказать, массив ссылок? Эта задача как раз и стояла изначально передо мной. И решение уже такой задачи следующее:

В этом случае мы получаем список только тех файлов, которые существуют.

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

Под словом «локальный» подразумевается, что скрипт и файлы для проверки находятся на одном сервере. Если у вас довольно большой массив ссылок – этот вариант самый лучший для решения задачи, так как мы делаем не запрос на сторонний сервер, а сканирование указанных директорий.

В этом способе используется функция «file_exists», и по аналогии с предыдущим вариантом просто заменяется часть скрипта:

И то же самое для массива ссылок:

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

Кстати говоря, делая один из заказов, именно этим способом мне удалось просканировать порядка 135 000 файлов всего за пару секунд.

Источник

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

Описание:

Проверяет наличие указанного файла или каталога.

Список параметров:

Путь к файлу или каталогу.

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

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

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

Замечание:

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

Если файлы недоступны из-за ограничений, налагаемых безопасным режимом, то данная функция вернет FALSE. Однако, эти файлы все еще могут быть подключены, если они располагаются в каталоге safe_mode_include_dir.

Замечание:

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

Замечание:

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

Примеры:

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

file_exists — Проверяет наличие указанного файла или каталога

file_exists

file_exists — Проверить наличие указанного файла или каталога

Описание

bool file_exists ( string filename )

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

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

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

См.также описания функций is_readable(), is_writable(), is_file() и file().

Смотрите также:
Все функции файл
Описание на ru2.php.net
Описание на php.ru

Вам нужно имя файла в кавычках как минимум (как строка):

Кроме того, убедитесь, что правильно проверен. И тогда он будет работать только тогда, когда активируется в вашей конфигурации PHP

Попробуйте вот так:

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

PHP, проверка существования/наличия удаленного файла

если это не 404, вы не можете использовать какие-либо обертки, чтобы увидеть, существует ли файл, и вы должны запросить свой cdn, используя какой-либо другой протокол, например FTP

Вот простейший способ проверить, существует ли файл:

php.net/manual/en/function.is-file.php возвращает true для (обычных) файлов:

возвращает true для обоих файлов и каталогов:

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

вы можете использовать cURL. Вы можете получить cURL только для того, чтобы дать вам заголовки, а не тело, которое могло бы сделать его быстрее. Плохой домен всегда может занять некоторое время, потому что вы будете ждать запроса на тайм-аут; вы, вероятно, можете изменить длину таймаута, используя cURL.

читает не только файлы, но и пути. поэтому, когда пуст, команда будет работать так, как если бы она была написана следующим образом:

Обычно я пишу это так:

Если вы используете завиток, вы можете попробовать следующий скрипт:

Ссылка URL: https://hungred.com/how-to/php-check-remote-email-url-image-link-exist/

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

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

Как в PHP проверить директорию на существование и удалить её?

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

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

Примеры

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

Ошибки

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

Вернуться к: Файловая система

Проверка на существование

В PHP есть два способа проверки директорий на существование. Первый заключается в использовании функции file_exists(). Принцип её работы обсуждался ранее в статье о правах доступа. Напомним, что функция принимает всего один строковой параметр — путь в файловой системе. Несмотря на то, что в названии содержится слово «file» она замечательно работает с директориями.

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

Заметка
Функции, отвечающие за проверку директорий на существование, могут возвращать false при отсутствии прав доступа. Такие вещи не зависят от PHP-скрипта, это уровень ответственности операционной системы.

Удаление директории

Для удаления директории в PHP используется функция rmdir(). В качестве первого параметра ей необходимо передать место расположения каталога. По аналогии с вышеизложенными примерами будут возвращены логические значения true или false.

Удаление директории может показаться простой задачей. Однако в большинстве случаев это не так. Функция rmdir() работает только с пустым каталогом и возвращает false, если внутри содержится что-то ещё. В таком случае нужно использовать рекурсивное удаление.

Рекурсивное удаление

Простого способа удаления заполненной директории не существует.

Ниже мы приводим два примера реализации подобного механизма. Его можно сохранить в виде функции и использовать в любой части программного кода.

Первым способом удаления директории в PHP является использование рекурсивной функции. То есть функции, которая вызывает сама себя пока выполняются определенные условия. Взгляните на пример, приведенный ниже. Он довольно прост для понимания.

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

Мы используем стандартную функцию scandir() для перебора всего содержимого каталога. Если мы натыкаемся на файл, вызываем функцию unlink(), а если на другую директорию, используем её имя для рекурсивного вызова.

Также в PHP есть два встроенных класса RecursiveDirectoryIterator и RecursiveIteratorIterator. Их можно использовать для перебора всех уровней вложенности указанной директории. Обратите внимание, при создании экземпляра класса RecursiveIteratorIterator мы используем второй параметр RecursiveIteratorIterator::CHILD_FIRST. Он заставляет проходить в цикле все файлы и каталоги, начиная от самых вложенных. Таким образом, можно обойтись без явного вызова рекурсивной функции.

Источник

file_exists

file_exists — Проверяет наличие указанного файла или каталога

Описание

Проверяет наличие указанного файла или каталога.

Список параметров

Путь к файлу или каталогу.

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

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

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

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

Примеры

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

Ошибки

Примечания

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

Коментарии

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

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.

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.

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.

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.

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

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

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

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

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

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

EXAMPLE:
File you are checking for: http://www.youserver.net/myfile.gif
Server IP: 10.0.0.125

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.

Here is a simpler version of url_exists:

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

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

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

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

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

file_exists() will return FALSE for broken links

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.

So
$url=»http://www.somewhere.org/index.htm»;
if (file_exists($url)) echo «Wow!\n»;
else echo «missing\n»;

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

$url=»http://www.somewhere.org/index.htm»;
if (false!==file($url)) echo «Wow!\n»;
else echo «missing\n»;

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

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

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.

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:

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.

Источник

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

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