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 ); }
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.
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.
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.
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'.
$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."; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With