Php does dir exists

is_dir

Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled open_basedir further restrictions may apply.

Return Values

Returns true if the filename exists and is a directory, false otherwise.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 is_dir() example

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

var_dump ( is_dir ( ‘..’ )); //one dir up
?>

The above example will output:

bool(false) bool(false) bool(true)

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

  • chdir() — Change directory
  • dir() — Return an instance of the Directory class
  • opendir() — Open directory handle
  • is_file() — Tells whether the filename is a regular file
  • is_link() — Tells whether the filename is a symbolic link

User Contributed Notes 21 notes

Just a note for anyone who encounters is_dir() returning false on CIFS mount points or directories within those mount points on 2.6.31 and newer kernels: Apparently in new kernels they’ve started using the CIFS serverino option by default. With Windows shares this causes huge inode numbers and which apparently can cause is_dir() to return false. Adding the noserverino option to the CIFS mount will prevent this. This may only occur on 32 systems but I don’t have a 64 bit install to test against.

Note that on Linux is_dir returns FALSE if a parent directory does not have +x (executable) set for the php process.

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

$i=0;
while($i <=$files_n)// "is_dir" only works from top directory, so append the $dir before the file
if (is_dir($dir.’/’.$files[$i])) <
$MyFileType[$i] = «D» ; // D for Directory
> else $MyFileType[$i] = «F» ; // F for File
>
// print itemNo, itemType(D/F) and itemname
echo ‘
‘.$i.’. ‘. $MyFileType[$i].’. ‘ .$files[$i] ;
$i++;
>
?>

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

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

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.

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:

for( $c = ‘A’ ; $c if( is_dir ( $c . ‘:’ ))
echo $c . ‘: ‘ ;
>
?>

which yielded:
A: C: D: E: F: G: H: I:

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):

$d = opendir(«./albums/mydir»);
while(false !== ($f = readdir($d))) echo «


«;
if(is_dir($f)) echo «Works:» . $f . ««;
>
>

However, this works properly for all directories:

$d = opendir(«./albums/mydir»);
while(false !== ($f = readdir($d))) echo «


«;
$dName = «./albums/mydir/» . $f;
if(is_dir($dName)) echo «Works:» . $dName . ««;
>
>

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

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 ($fname == ‘.’) continue; // skip dirs . and .. by first char test

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.

if (is_dir(«myphotos\» . $fname)) call_own_subdir_process; // skip subdirs

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

One note regarding checking for empty directories :
>>echo (count(glob(«$dir/*»)) === 0) ? ‘Empty’ : ‘Not empty’;
This does not work correctly on Linux.
The ‘.’ and ‘..’ will always be returned even if no files are present in the directory.

is_dir() doesn’t work with a directory that has the name «0» (a single zero). Neither does realpath().

This is my experience with PHP 7.4.

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

An example:
symlink(«.», «testlink»);
var_dump(is_dir(«testlink»));
unlink(«testlink»);
?>

(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.)

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

$dir = ‘directory’ ;
echo ( count ( glob ( » $dir /*» )) === 0 ) ? ‘Empty’ : ‘Not empty’ ;
?>

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:

function is_dir_LFS($path) return ((‘d’==substr(exec(«ls -dl ‘$path'»),0,1))?(true):(false));
>

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

this function bypasses open_basedir restrictions.
function my_is_dir($dir)
// bypasses open_basedir restrictions of is_dir and fileperms
$tmp_cmd = `ls -dl $dir`;
$dir_flag = $tmp_cmd[0];
if($dir_flag!=»d»)
// not d; use next char (first char might be ‘s’ and is still directory)
$dir_flag = $tmp_cmd[1];
>
return ($dir_flag==»d»);
>
?>

example:
.
echo is_dir(«/somewhere/i/dont/have/access/to»);
?>
output:
Warning: open_basedir restriction in effect

.
echo my_is_dir(«/somewhere/i/dont/have/access/to»);
?>
output:
true (or false, depending whether it is or not. )


visit puremango.co.uk for other such wonders

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

// Open a directory, and read its contents
if (is_dir($dir)) echo $dir.»
«; // will not appear if above fails
if ($dh = opendir($dir)) echo $dir.»
«; // will not appear if above fails
while (($file = readdir($dh)) !== false) echo «filename:» . $file . «
«;
echo $dir.»
«; // will not appear if above fails
>
closedir($dh);
>
>

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

function scan_Dir ( $dir ) $arrfiles = array();
if ( is_dir ( $dir )) if ( $handle = opendir ( $dir )) chdir ( $dir );
while ( false !== ( $file = readdir ( $handle ))) <
if ( $file != «.» && $file != «..» ) <
if ( is_dir ( $file )) <
$arr = scan_Dir ( $file );
foreach ( $arr as $value ) $arrfiles [] = $dir . «/» . $value ;
>
> else $arrfiles [] = $dir . «/» . $file ;
>
>
>
chdir ( «../» );
>
closedir ( $handle );
>
return $arrfiles ;
>

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

function is_empty_dir ( $dir )
if (( $files = @ scandir ( $dir )) && count ( $files ) <= 2 ) return true ;
>
return false ;
>
?>

NOTE: you should obviously be checking beforehand if $dir is actually a directory, and that it is readable, as only relying on this you would assume that in both cases you have a non-empty readable directory.

Источник

Check if a directory exists php

check directory exists in php php file exist php check if file exists php check if folder exists Question: why won’t this work? Syntax: Returns if the file or directory specified by filename exists; otherwise.

Check if a directory exists php

check directory exists in php

php file exist

php check if file exists

if (!file_exists(‘http://mysite.com/images/thumbnail_1286954822.jpg’))

php check if folder exists

Check if file exists in php, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

Check if file exists in php

if (!(file_exists(http://mysite.com/images/thumbnail_1286954822.jpg)))
if (!file_exists('http://example.com/images/thumbnail_1286954822.jpg'))

file_exists checks whether a file exist in the specified path or not.

file_exists ( string $filename ) 

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

$filename = BASE_DIR."images/a/test.jpg"; if (file_exists($filename))< echo "File exist."; >else

Another alternative method you can use getimagesize(), it will return 0(zero) if file/directory is not available in the specified path.

Based on your comment to Haim, is this a file on your own server? If so, you need to use the file system path, not url (e.g. file_exists( ‘/path/to/images/thumbnail.jpg’ ) ).

Check if file exists in directory c# Code Example, how to check if a file is running in c#. C# winform if document doesn’t exist. c# if a file directory exists. c# if file exists contains. c# test if file path exists. c# test file exists. c# look if file exists by just nowing its name. c#.net check if file exists. check file exist in c# from path.

How can I use PHP to check if a directory is empty?

I am using the following script to read a directory. If there is no file in the directory it should say empty. The problem is, it just keeps saying the directory is empty even though there ARE files inside and vice versa.

It seems that you need scandir instead of glob, as glob can’t see unix hidden files.

else < echo "the folder is NOT empty"; >function is_dir_empty($dir) < if (!is_readable($dir)) return null; return (count(scandir($dir)) == 2); >?> 

Note that this code is not the summit of efficiency, as it’s unnecessary to read all the files only to tell if directory is empty. So, the better version would be

function dir_is_empty($dir) < $handle = opendir($dir); while (false !== ($entry = readdir($handle))) < if ($entry != "." && $entry != "..") < closedir($handle); return false; >> closedir($handle); return true; > 

By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An

expression already returns Empty or Non Empty in terms of programming language, false or true respectively — so, you can use the very result in control structures like IF() without any intermediate values

I think using the FilesystemIterator should be the fastest and easiest way:

// PHP 5 >= 5.3.0 $iterator = new \FilesystemIterator($dir); $isDirEmpty = !$iterator->valid(); 

Or using class member access on instantiation:

// PHP 5 >= 5.4.0 $isDirEmpty = !(new \FilesystemIterator($dir))->valid(); 

This works because a new FilesystemIterator will initially point to the first file in the folder — if there are no files in the folder, valid() will return false . (see documentation here.)

As pointed out by abdulmanov.ilmir, optionally check if the directory exists before using the FileSystemIterator because otherwise it’ll throw an UnexpectedValueException .

How to check if Directory already Exists in MFC(VC++)?, I am using below code to get current application Path and there i am creating NDSLog folder so that all my Logfiles should place there , now i want to check the condition if NDSLog folder already exists dont create it .How to do that ? Thanks. char strPathName[_MAX_PATH]; ::GetModuleFileName(NULL, …

How do I check if a directory is writeable in PHP?

Does anyone know how I can Check to see if a directory is writeable in PHP?

The function is_writable doesn’t work for folders.

Edit: It does work. See the accepted answer.

Yes, it does work for folders.

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

to be more specific for owner/group/world

$dir_writable = substr(sprintf('%o', fileperms($folder)), -4) == "0774" ? "true" : "false"; 

You may be sending a complete file path to the is_writable() function. is_writable() will return false if the file doesn’t already exist in the directory. You need to check the directory itself with the filename removed, if this is the case. If you do that, is_writable will correctly tell you whether the directory is writable or not. If $file contains your file path do this:

$file_directory = dirname($file); 

Then use is_writable($file_directory) to determine if the folder is writable.

I hope this helps someone.

Get Current Directory Name and Path in PHP, Use the dirname () Function to Get the Current Directory Name in PHP We can also use the dirname () function to get the current directory name in PHP. The function returns the path of the parent directory. It accepts two parameters where the first one is the path and the second one is levels. Levels indicate the number of …

Источник

Читайте также:  Pip3 install python can
Оцените статью