streetparade
streetparade

Reputation: 32878

How to test if a directory already exist in PHP?

How can i test if a directory already exist and if not create one in PHP?

Upvotes: 1

Views: 5003

Answers (4)

Ram Ch. Bachkheti
Ram Ch. Bachkheti

Reputation: 2639

Use This:

if(file_exists("Directory path") && is_dir("Directory path")) {

//Your Code;

}

Upvotes: 0

John Conde
John Conde

Reputation: 219804

To expand on the answer above based on the questioner's comments:

$filename = "/tmp";
if (!is_dir($filename)) {
    mkdir($filename);
}

You need to use mkdir() to actually make the directory.

Upvotes: 2

Veger
Veger

Reputation: 37905

Try this:

$dir = "/path/to/dir";
if(is_dir($dir) == false)
    mkdir($dir);

If you want the complete path the be created (if not present), set recusive parameter to true.

See documentation of mkdir for more information.

Upvotes: 1

Dan Soap
Dan Soap

Reputation: 10248

Try this:

$filename = "/tmp";
if (!file_exists($filename))
    echo $filename, " does not exist";
elseif (!is_dir($filename))
    echo $filename, " is not a directory";
else
    echo "Directory ", $filename, " already exists";

file_exists checks if the path/file exists and is_dir checks whether the given filename is a directory.

Edit:

to create the directory afterwards, call

mkdir($filename);

Upvotes: 7

Related Questions