php if dir exist

Проверить существование папки php функция is_dir

Существует папка или нет!? Проверить существование папки в php? функция для проверки существующий папки. Что такое is_dir описание, как работает is_dir, зачем нужна функция is_dir.

Можно использовать и file_exists, но эта функция не определяет, что это директория(папка)!

Все о существовании или отсутствия папки на сервере

Что такое is_dir

Все же немного теории:

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

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

Если папка существует и это не файл, возвращает TRUE => иначе возвращается FALSE.

С теорией о is_dir покончили

Приступим к практике с использованием is_dir!

Применение функции is_dir к файлу

Одно дело, когда нам учебник говорит, что функция определяет это файл и ли папка. и совсем другое дело практика!

Результат работы функции is_dir для файла:

Как видим, функция, для существующего файла, функция is_dir возвращает false, что говорит нам, что данный путь, не является папкой.

Проверка несуществующей папки с помощью is_dir

Результат работы функции is_dir для несуществующей папки:

Проверка существования папки с помощью is_dir к существующей папке

Далее нам потребуется существующая папка и существующий путь до папки вставим в функцию is_dir :

Результат работы функции is_dir для несуществующей папки:

Для существующей папки is_dir возвращает true

Сообщение системы комментирования :

Форма пока доступна только админу. скоро все заработает. надеюсь.

Источник

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»)) < //

Источник

Create a folder if it doesn’t already exist

I’ve run into a few cases with WordPress installs with Bluehost where I’ve encountered errors with my WordPress theme because the uploads folder wp-content/uploads was not present.

Apparently the Bluehost cPanel WordPress installer does not create this folder, though HostGator does.

So I need to add code to my theme that checks for the folder and creates it otherwise.

php if dir exist. Смотреть фото php if dir exist. Смотреть картинку php if dir exist. Картинка про php if dir exist. Фото php if dir exist

20 Answers 20

Note that 0777 is already the default mode for directories and may still be modified by the current umask.

Here is the missing piece. You need to pass ‘recursive’ flag as third argument (boolean true) in mkdir call like this:

php if dir exist. Смотреть фото php if dir exist. Смотреть картинку php if dir exist. Картинка про php if dir exist. Фото php if dir exist

Something a bit more universal since this comes up on google. While the details are more specific, the title of this question is more universal.

This will take a path, possibly with a long chain of uncreated directories, and keep going up one directory until it gets to an existing directory. Then it will attempt to create the next directory in that directory, and continue till it’s created all the directories. It returns true if successful.

Could be improved by providing a stopping level so it just fails if it goes beyond user folder or something and by including permissions.

What about a helper function like this:

It will return true if the directory was successfully created or already exists, and false if the directory couldn’t be created.

A better alternative is this (shouldn’t give any warnings):

Faster way to create folder:

php if dir exist. Смотреть фото php if dir exist. Смотреть картинку php if dir exist. Картинка про php if dir exist. Фото php if dir exist

Recursively create directory path:

Inspired by Python’s os.makedirs()

Within WordPress there’s also the very handy function wp_mkdir_p which will recursively create a directory structure.

Source for reference:-

php if dir exist. Смотреть фото php if dir exist. Смотреть картинку php if dir exist. Картинка про php if dir exist. Фото php if dir exist

Better to use wp_mkdir_p function for it. This function will recursively create a folder with the correct permissions. Also, you can skip folder exists condition because it will be check before creating.

php if dir exist. Смотреть фото php if dir exist. Смотреть картинку php if dir exist. Картинка про php if dir exist. Фото php if dir exist

php if dir exist. Смотреть фото php if dir exist. Смотреть картинку php if dir exist. Картинка про php if dir exist. Фото php if dir exist

This is the most up-to-date solution without error suppression:

To create a folder if it doesn’t already exist

Considering the question’s environment.

so, We can simply code:

Explanation:

We don’t have to pass any parameter or check if folder exists or even pass mode parameter unless needed; for the following reasons:

This is just another way to look into the question and not claiming a better or most optimal solution.

Tested on PHP7, Production Server, Linux

Источник

mkdir

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

mkdir — Создаёт директорию

Описание

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

Аргумент permissions игнорируется в Windows.

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

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Ошибки

Примеры

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

Пример #2 Использование mkdir() с параметром recursive

// Желаемая структура папок
$structure = ‘./depth1/depth2/depth3/’ ;

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

User Contributed Notes 40 notes

When using the recursive parameter bear in mind that if you’re using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie:

May result in «/test1/test2» having a mode of 0777 but «/test1» still having a mode of 0755 from the mkdir() call. You’d need to do:

Please note that in a shared environment I failed to take into account an existing umask when I did a mkdir(dirname, 0755). This ended up creating the directory (function returned true), but I didn’t have rights to do anything inside the folder, nor could I even view that it existed via ftp.

However, file_exists(dirname) returned true. Eventually I figured out what happened and was able to rmdir(dirname), then created the directory correctly.

So, when writing scripts you expect to be portable, either use umask to set your umask accordingly, or do a straight mkdir(dirname) followed by chmod(dirname, 0755) (or whatever it is you’re looking for). If you make the same mistake I did, you should be able to rmdir() or chmod() the folder so it’s accessible.

One small correction on a note from Frank in June 2006 on recursive directories under Windows.

Franks note stated:

This will work a bit better 🙂

Источник

file_exists

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

file_exists — Checks whether a file or directory exists

Description

Checks whether a file or directory exists.

Parameters

Path to the file or directory.

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

Return Values

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

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

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.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 Testing whether a file exists

Notes

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

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

See Also

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

Источник

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

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