Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a directory exists? "is_dir", "file_exists" or both?

Tags:

php

I want to create a directory if it does not exist already.

Is using the is_dir function enough for that purpose?

if ( !is_dir( $dir ) ) {     mkdir( $dir );        } 

Or should I combine is_dir with file_exists?

if ( !file_exists( $dir ) && !is_dir( $dir ) ) {     mkdir( $dir );        }  
like image 219
Peter Avatar asked Mar 24 '11 21:03

Peter


People also ask

How do you check folder is created or not PHP?

The file_exists() function in PHP is an inbuilt function which is used to check whether a file or directory exists or not. The path of the file or directory you want to check is passed as a parameter to the file_exists() function which returns True on success and False on failure.

How do you check directory is exist in C#?

The Directory static class in the System.IO namespace provides the Exists() method to check the existence of a directory on the disk. This method takes the path of the directory as a string input, and returns true if the directory exists at the specified path; otherwise, it returns false.

How do you check if a directory exists or not in Java?

io. File. exists() is used to check whether a file or a directory exists or not. This method returns true if the file or directory specified by the abstract path name exists and false if it does not exist.


2 Answers

Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.

like image 151
Marc B Avatar answered Sep 24 '22 12:09

Marc B


$dirname = $_POST["search"]; $filename = "/folder/" . $dirname . "/";  if (!file_exists($filename)) {     mkdir("folder/" . $dirname, 0777);     echo "The directory $dirname was successfully created.";     exit; } else {     echo "The directory $dirname exists."; } 
like image 44
Maher Avatar answered Sep 22 '22 12:09

Maher