q0987
q0987

Reputation: 35982

PHP - why is_dir returns TRUE when a dir doesn't exist?

My current directory structure is as follows:

C:\xampp\htdocs\PHP_Upload_Image_MKDIR

In other words, the following directories do NOT exist at all.

C:\xampp\htdocs\PHP_Upload_Image_MKDIR\uploaded
C:\xampp\htdocs\PHP_Upload_Image_MKDIR\uploaded\s002

The problem is that when I run the following script, the function is_dir always return TRUE.

Based on the manual, https://www.php.net/manual/en/function.is-dir.php is_dir: Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Do I miss something here?

Thank you

$userID = 's002';
$uploadFolder = '/PHP_Upload_Image_MKDIR/uploaded/';
$userDir = $uploadFolder . $userID;
echo '<br/>$userDir: ' . $userDir . '<br/>';

if ( is_dir ($userDir))
{
  echo "dir exists"; // always hit here!!!
}
else 
{
  echo "dir doesn't exist";
}

mkdir($userDir, 0700);
C:\xampp\htdocs\PHP_Upload_Image_MKDIR>dir /ah
 Volume in drive C is System
 Volume Serial Number is 30B8-2BB2

 Directory of C:\xampp\htdocs\PHP_Upload_Image_MKDIR

File Not Found

C:\xampp\htdocs\PHP_Upload_Image_MKDIR>


//////////////////////////////////////////////////////////

Based on Artefacto's comments:

Here is the output of C:\PHP_Upload_Image_MKDIR\uploaded\s005
 echo '<br/>' . realpath($userDir) . '<br/>';

Thank you for the solutions.

Best wishes

Upvotes: 6

Views: 3271

Answers (3)

efritz
efritz

Reputation: 5203

Also, it seems as if the dir you are checking is PHP_Uploaded_Image_MKDIR/uploaded/s002, which is an absolute path starting from the root filesystem.

Try prepending C:\xampp\htdocs\ to this and see if it works then. Also, check to see if the folder exists at the root of the volume.

Upvotes: 3

Peter Ajtai
Peter Ajtai

Reputation: 57695

If you've run that script more than once, then is_dir($userDir) will return true because of this line (the last one) in your script:

mkdir($userDir, 0700);

You can use rmdir() or some other method to delete it.

To test is_dir(), try a directory name that has never been used / created. Something like the following should return false, when it does, you know that is_dir() works:

if ( is_dir ("/PHP_Upload_Image_MKDIR/uploaded/lkjlkjlkjkl"))

Upvotes: 2

Moe Sweet
Moe Sweet

Reputation: 3721

Try file_exists() instead.

http://php.net/manual/en/function.file-exists.php

Upvotes: 2

Related Questions