Related
I've run into a few cases with WordPress installs with Bluehost where I've encountered errors with my WordPress theme because the uploads folder wp-content/uploads was not present.
Apparently the Bluehost cPanel WordPress installer does not create this folder, though HostGator does.
So I need to add code to my theme that checks for the folder and creates it otherwise.
Try this, using mkdir:
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Note that 0777 is already the default mode for directories and may still be modified by the current umask.
Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:
mkdir('path/to/directory', 0755, true);
Here is something a bit more universal since this comes up on Google. While the details are more specific, the title of this question is more universal.
/**
* recursively create a long directory path
*/
function createPath($path) {
if (is_dir($path))
return true;
$prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
$return = createPath($prev_path);
return ($return && is_writable($prev_path)) ? mkdir($path) : false;
}
This will take a path, possibly with a long chain of uncreated directories, and keep going up one directory until it gets to an existing directory. Then it will attempt to create the next directory in that directory, and continue till it's created all the directories. It returns true if successful.
It could be improved by providing a stopping level so it just fails if it goes beyond the user folder or something and by including permissions.
Use a helper function like this:
function makeDir($path)
{
$ret = mkdir($path); // use #mkdir if you want to suppress warnings/errors
return $ret === true || is_dir($path);
}
It will return true if the directory was successfully created or already exists, and false if the directory couldn't be created.
A better alternative is this (shouldn't give any warnings):
function makeDir($path)
{
return is_dir($path) || mkdir($path);
}
A faster way to create a folder:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Recursively create the directory path:
function makedirs($dirpath, $mode=0777) {
return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}
Inspired by Python's os.makedirs()
The best way is to use the wp_mkdir_p function. This function will recursively create a folder with the correct permissions.
Also, you can skip folder exists condition because the function returns:
true when the directory was created or existed before
false if you can't create the directory.
Example:
$path = 'path/to/directory';
if ( wp_mkdir_p( $path ) ) {
// Directory exists or was created.
}
More: https://developer.wordpress.org/reference/functions/wp_mkdir_p/
Within WordPress, there's also the very handy function wp_mkdir_p which will recursively create a directory structure.
Source for reference:
function wp_mkdir_p( $target ) {
$wrapper = null;
// Strip the protocol
if( wp_is_stream( $target ) ) {
list( $wrapper, $target ) = explode( '://', $target, 2 );
}
// From php.net/mkdir user contributed notes
$target = str_replace( '//', '/', $target );
// Put the wrapper back on the target
if( $wrapper !== null ) {
$target = $wrapper . '://' . $target;
}
// Safe mode fails with a trailing slash under certain PHP versions.
$target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
if ( empty($target) )
$target = '/';
if ( file_exists( $target ) )
return #is_dir( $target );
// We need to find the permissions of the parent folder that exists and inherit that.
$target_parent = dirname( $target );
while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
$target_parent = dirname( $target_parent );
}
// Get the permission bits.
if ( $stat = #stat( $target_parent ) ) {
$dir_perms = $stat['mode'] & 0007777;
} else {
$dir_perms = 0777;
}
if ( #mkdir( $target, $dir_perms, true ) ) {
// If a umask is set that modifies $dir_perms, we'll have to re-set the $dir_perms correctly with chmod()
if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
$folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
#chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
}
}
return true;
}
return false;
}
I needed the same thing for a login site. I needed to create a directory with two variables.
The $directory is the main folder where I wanted to create another sub-folder with the users license number.
include_once("../include/session.php");
$lnum = $session->lnum; // Users license number from sessions
$directory = uploaded_labels; // Name of directory that folder is being created in
if (!file_exists($directory . "/" . $lnum)) {
mkdir($directory . "/" . $lnum, 0777, true);
}
This is the most up-to-date solution without error suppression:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory');
}
For your specific question about WordPress, use the following code:
if (!is_dir(ABSPATH . 'wp-content/uploads')) wp_mkdir_p(ABSPATH . 'wp-content/uploads');
Function Reference: WordPress wp_mkdir_p. ABSPATH is the constant that returns WordPress working directory path.
There is another WordPress function named wp_upload_dir(). It returns the upload directory path and creates a folder if doesn't already exists.
$upload_path = wp_upload_dir();
The following code is for PHP in general.
if (!is_dir('path/to/directory')) mkdir('path/to/directory', 0777, true);
Function reference: PHP is_dir()
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
Here you go.
if (!is_dir('path/to/directory')) {
if (!mkdir('path/to/directory', 0777, true) && !is_dir('path/to/directory')) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', 'path/to/directory'));
}
}
You can try also:
$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);
If you want to avoid the file_exists vs. is_dir problem, I would suggest you to look here.
I tried this and it only creates the directory if the directory does not exist. It does not care if there is a file with that name.
/* Creates the directory if it does not exist */
$path_to_directory = 'path/to/directory';
if (!file_exists($path_to_directory) && !is_dir($path_to_directory)) {
mkdir($path_to_directory, 0777, true);
}
To create a folder if it doesn't already exist
Considering the question's environment.
WordPress.
Webhosting server.
Assuming it's Linux, not Windows running PHP.
And quoting from: mkdir
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive =
FALSE [, resource $context ]]] )
The manual says that the only required parameter is the $pathname!
So, we can simply code:
<?php
error_reporting(0);
if(!mkdir('wp-content/uploads')){
// Todo
}
?>
Explanation:
We don't have to pass any parameter or check if the folder exists or even pass the mode parameter unless needed; for the following reasons:
The command will create the folder with 0755 permission (the shared hosting folder's default permission) or 0777, the command's default.
mode is ignored on Windows hosting running PHP.
Already the mkdir command has a built-in checker for if the folder exists; so we need to check the return only True|False ; and it’s not an error; it’s a warning only, and Warning is disabled on the hosting servers by default.
As per speed, this is faster if warning disabled.
This is just another way to look into the question and not claiming a better or most optimal solution.
It was tested on PHP 7, production server, and Linux
if (!is_dir('path_directory')) {
#mkdir('path_directory');
}
We can create folder using mkdir. Also we can set permission for it.
Value Permission
0 cannot read, write or execute
1 can only execute
2 can only write
3 can write and execute
4 can only read
5 can read and execute
6 can read and write
7 can read, write and execute
<?PHP
// Making a directory with the provision
// of all permissions to the owner and
// the owner's user group
mkdir("/documents/post/", 0770, true)
?>
As a complement to current solutions, a utility function.
function createDir($path, $mode = 0777, $recursive = true) {
if(file_exists($path)) return true;
return mkdir($path, $mode, $recursive);
}
createDir('path/to/directory');
It returns true if already exists or successfully created. Else it returns false.
We should always modularise our code and I've written the same check it below...
We first check the directory. If the directory is absent, we create the directory.
$boolDirPresents = $this->CheckDir($DirectoryName);
if (!$boolDirPresents) {
$boolCreateDirectory = $this->CreateDirectory($DirectoryName);
if ($boolCreateDirectory) {
echo "Created successfully";
}
}
function CheckDir($DirName) {
if (file_exists($DirName)) {
echo "Dir Exists<br>";
return true;
} else {
echo "Dir Not Absent<br>";
return false;
}
}
function CreateDirectory($DirName) {
if (mkdir($DirName, 0777)) {
return true;
} else {
return false;
}
}
You first need to check if directory exists file_exists('path_to_directory')
Then use mkdir(path_to_directory) to create a directory
mkdir( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool
More about mkdir() here
Full code here:
$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
mkdir($structure);
}
I am wondering how I can create a function that states:
if a file of name Setup.php exist twice in a folder and/or it's associated sub folders, return a message. if a file with the extension .css exists more then once in a folder or any of its sub folders, return a message
This function would have to be recursive, due to sub folders. and its fine to hard code 'Setup.php' or '.css' as they are the only things looked for.
What I currently have is a bit messy but does the trick (refactoring will come after I figure out this issue)
protected function _get_files($folder_name, $type){
$actual_dir_to_use = array();
$array_of_files[] = null;
$temp_array = null;
$path_info[] = null;
$array_of_folders = array_filter(glob(CUSTOM . '/' .$folder_name. '/*'), 'is_dir');
foreach($array_of_folders as $folders){
$array_of_files = $this->_fileHandling->dir_tree($folders);
if(isset($array_of_files) && !empty($array_of_files)){
foreach($array_of_files as $files){
$path_info = pathinfo($files);
if($type == 'css'){
if($path_info['extension'] == 'css'){
$actual_dir_to_use[] = $folders;
}
}
if($type == 'php'){
if($path_info['filename'] == 'Setup' && $path_info['extension'] == 'php'){
$temp_array[] = $folders;
$actual_dir_to_use[] = $folders;
}
}
}
}
$array_of_files = array();
$path_info = array();
}
return $actual_dir_to_use;
}
if you pass in say, packages and php into the function I will look through the packages folder and return all the sub-folder names, (eg: path/to/apples, path/to/bananas, path/to/fruit, path/to/cat, path/to/dog) that contain Setup with an extension of php.
The problem is if apples/ contains more then one Setup.php then I get: path/to/apples, path/to/apples, path/to/bananas, path/to/fruit, path/to/cat, path/to/dog
So I need to modify this function, or write a separate one, that sates the above sudo code.
problem? I don't know where to begin. So I am here asking for help.
You can find the class ipDirLiterator here - deleting all files in except the one running the delete code.
i hope you got it.
<?php
$directory = dirname( __FILE__ )."/test/";
$actual_dir_to_use = array();
$to_find = "php";
$literator = new ipDirLiterator( $directory, array( "file" => "file_literator", "dir" => "dir_literator" ) );
$literator->literate();
function file_literator( $file ) {
global $actual_dir_to_use, $to_find;
// use print_r( $file ) to see what all are inside $file
$filename = $file["filename"]; // the file name
$filepath = $file["pathname"]; // absolute path to file
$folder = $file["path"]; // the folder where the current file contains
$extens = strtolower( $file["extension"] );
if ( $to_find === "php" && $filename === "Setup.php" ) {
$actual_dir_to_use[] = $folder;
}
if ( $to_find === "css" && $extens === "css" ) {
$actual_dir_to_use[] = $folder;
}
}
function dir_literator( $file ) {}
print_r( $actual_dir_to_use );
// or check
if ( count( $actual_dir_to_use ) > 1 ) {
// here multiple files
}
?>
Q: Is this a homework assignment?
Assuming "no", then:
1) No, the function doesn't need to be recursive
2) Under Linux, you could find matching files like this: find /somefolder -name somefile -print
3) Similarly, you can detect if a match occurs zero, once or more than once in the path like this:
find /somefolder -name somefile -print|wc -l
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 );
}
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'.
$filename = "/folder/" . $dirname . "/";
if (file_exists($filename)) {
echo "The directory $dirname exists.";
} else {
mkdir("folder/" . $dirname, 0755);
echo "The directory $dirname was successfully created.";
exit;
}
I think realpath() may be the best way to validate if a path exist
http://www.php.net/realpath
Here is an example function:
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (long version)
* #param string $folder the path being checked.
* #return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
if($path !== false AND is_dir($path))
{
// Return canonicalized absolute pathname
return $path;
}
// Path/folder does not exist
return false;
}
Short version of the same function
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (sort version)
* #param string $folder the path being checked.
* #return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
Output examples
<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input); // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output); // bool(false)
/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input); // string(5) "/home"
var_dump($output); // string(5) "/home"
/** CASE 3 **/
$input = '/home/..';
var_dump($input); // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output); // string(1) "/"
Usage
<?php
$folder = '/foo/bar';
if(FALSE !== ($path = folder_exist($folder)))
{
die('Folder ' . $path . ' already exist');
}
mkdir($folder);
// Continue do stuff
Second variant in question post is not ok, because, if you already have file with the same name, but it is not a directory, !file_exists($dir) will return false, folder will not be created, so error "failed to open stream: No such file or directory" will be occured. In Windows there is a difference between 'file' and 'folder' types, so need to use file_exists() and is_dir() at the same time, for ex.:
if (file_exists('file')) {
if (!is_dir('file')) { //if file is already present, but it's not a dir
//do something with file - delete, rename, etc.
unlink('file'); //for example
mkdir('file', NEEDED_ACCESS_LEVEL);
}
} else { //no file exists with this name
mkdir('file', NEEDED_ACCESS_LEVEL);
}
I had the same doubt, but see the PHP docu:
https://www.php.net/manual/en/function.file-exists.php
https://www.php.net/manual/en/function.is-dir.php
You will see that is_dir() has both properties.
Return Values is_dir
Returns TRUE if the filename exists and is a directory, FALSE otherwise.
$year = date("Y");
$month = date("m");
$filename = "../".$year;
$filename2 = "../".$year."/".$month;
if(file_exists($filename)){
if(file_exists($filename2)==false){
mkdir($filename2,0777);
}
}else{
mkdir($filename,0777);
}
$save_folder = "some/path/" . date('dmy');
if (!file_exists($save_folder)) {
mkdir($save_folder, 0777);
}
This is an old, but still topical question. Just test with the is_dir() or file_exists() function for the presence of the . or .. file in the directory under test. Each directory must contain these files:
is_dir("path_to_directory/.");
Well instead of checking both, you could do if(stream_resolve_include_path($folder)!==false). It is slower but kills two birds in one shot.
Another option is to simply ignore the E_WARNING, not by using #mkdir(...); (because that would simply waive all possible warnings, not just the directory already exists one), but by registering a specific error handler before doing it:
namespace com\stackoverflow;
set_error_handler(function($errno, $errm) {
if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();
This is how I do
if(is_dir("./folder/test"))
{
echo "Exist";
}else{
echo "Not exist";
}
A way to check if a path is directory can be following:
function isDirectory($path) {
$all = #scandir($path);
return $all !== false;
}
NOTE: It will return false for non-existant path too, but works perfectly for UNIX/Windows
i think this is fast solution for dir check.
$path = realpath($Newfolder);
if (!empty($path)){
echo "1";
}else{
echo "0";
}
I've run into a few cases with WordPress installs with Bluehost where I've encountered errors with my WordPress theme because the uploads folder wp-content/uploads was not present.
Apparently the Bluehost cPanel WordPress installer does not create this folder, though HostGator does.
So I need to add code to my theme that checks for the folder and creates it otherwise.
Try this, using mkdir:
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Note that 0777 is already the default mode for directories and may still be modified by the current umask.
Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:
mkdir('path/to/directory', 0755, true);
Here is something a bit more universal since this comes up on Google. While the details are more specific, the title of this question is more universal.
/**
* recursively create a long directory path
*/
function createPath($path) {
if (is_dir($path))
return true;
$prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
$return = createPath($prev_path);
return ($return && is_writable($prev_path)) ? mkdir($path) : false;
}
This will take a path, possibly with a long chain of uncreated directories, and keep going up one directory until it gets to an existing directory. Then it will attempt to create the next directory in that directory, and continue till it's created all the directories. It returns true if successful.
It could be improved by providing a stopping level so it just fails if it goes beyond the user folder or something and by including permissions.
Use a helper function like this:
function makeDir($path)
{
$ret = mkdir($path); // use #mkdir if you want to suppress warnings/errors
return $ret === true || is_dir($path);
}
It will return true if the directory was successfully created or already exists, and false if the directory couldn't be created.
A better alternative is this (shouldn't give any warnings):
function makeDir($path)
{
return is_dir($path) || mkdir($path);
}
A faster way to create a folder:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Recursively create the directory path:
function makedirs($dirpath, $mode=0777) {
return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}
Inspired by Python's os.makedirs()
The best way is to use the wp_mkdir_p function. This function will recursively create a folder with the correct permissions.
Also, you can skip folder exists condition because the function returns:
true when the directory was created or existed before
false if you can't create the directory.
Example:
$path = 'path/to/directory';
if ( wp_mkdir_p( $path ) ) {
// Directory exists or was created.
}
More: https://developer.wordpress.org/reference/functions/wp_mkdir_p/
Within WordPress, there's also the very handy function wp_mkdir_p which will recursively create a directory structure.
Source for reference:
function wp_mkdir_p( $target ) {
$wrapper = null;
// Strip the protocol
if( wp_is_stream( $target ) ) {
list( $wrapper, $target ) = explode( '://', $target, 2 );
}
// From php.net/mkdir user contributed notes
$target = str_replace( '//', '/', $target );
// Put the wrapper back on the target
if( $wrapper !== null ) {
$target = $wrapper . '://' . $target;
}
// Safe mode fails with a trailing slash under certain PHP versions.
$target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
if ( empty($target) )
$target = '/';
if ( file_exists( $target ) )
return #is_dir( $target );
// We need to find the permissions of the parent folder that exists and inherit that.
$target_parent = dirname( $target );
while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
$target_parent = dirname( $target_parent );
}
// Get the permission bits.
if ( $stat = #stat( $target_parent ) ) {
$dir_perms = $stat['mode'] & 0007777;
} else {
$dir_perms = 0777;
}
if ( #mkdir( $target, $dir_perms, true ) ) {
// If a umask is set that modifies $dir_perms, we'll have to re-set the $dir_perms correctly with chmod()
if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
$folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
#chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
}
}
return true;
}
return false;
}
I needed the same thing for a login site. I needed to create a directory with two variables.
The $directory is the main folder where I wanted to create another sub-folder with the users license number.
include_once("../include/session.php");
$lnum = $session->lnum; // Users license number from sessions
$directory = uploaded_labels; // Name of directory that folder is being created in
if (!file_exists($directory . "/" . $lnum)) {
mkdir($directory . "/" . $lnum, 0777, true);
}
This is the most up-to-date solution without error suppression:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory');
}
For your specific question about WordPress, use the following code:
if (!is_dir(ABSPATH . 'wp-content/uploads')) wp_mkdir_p(ABSPATH . 'wp-content/uploads');
Function Reference: WordPress wp_mkdir_p. ABSPATH is the constant that returns WordPress working directory path.
There is another WordPress function named wp_upload_dir(). It returns the upload directory path and creates a folder if doesn't already exists.
$upload_path = wp_upload_dir();
The following code is for PHP in general.
if (!is_dir('path/to/directory')) mkdir('path/to/directory', 0777, true);
Function reference: PHP is_dir()
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
Here you go.
if (!is_dir('path/to/directory')) {
if (!mkdir('path/to/directory', 0777, true) && !is_dir('path/to/directory')) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', 'path/to/directory'));
}
}
You can try also:
$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);
If you want to avoid the file_exists vs. is_dir problem, I would suggest you to look here.
I tried this and it only creates the directory if the directory does not exist. It does not care if there is a file with that name.
/* Creates the directory if it does not exist */
$path_to_directory = 'path/to/directory';
if (!file_exists($path_to_directory) && !is_dir($path_to_directory)) {
mkdir($path_to_directory, 0777, true);
}
To create a folder if it doesn't already exist
Considering the question's environment.
WordPress.
Webhosting server.
Assuming it's Linux, not Windows running PHP.
And quoting from: mkdir
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive =
FALSE [, resource $context ]]] )
The manual says that the only required parameter is the $pathname!
So, we can simply code:
<?php
error_reporting(0);
if(!mkdir('wp-content/uploads')){
// Todo
}
?>
Explanation:
We don't have to pass any parameter or check if the folder exists or even pass the mode parameter unless needed; for the following reasons:
The command will create the folder with 0755 permission (the shared hosting folder's default permission) or 0777, the command's default.
mode is ignored on Windows hosting running PHP.
Already the mkdir command has a built-in checker for if the folder exists; so we need to check the return only True|False ; and it’s not an error; it’s a warning only, and Warning is disabled on the hosting servers by default.
As per speed, this is faster if warning disabled.
This is just another way to look into the question and not claiming a better or most optimal solution.
It was tested on PHP 7, production server, and Linux
if (!is_dir('path_directory')) {
#mkdir('path_directory');
}
We can create folder using mkdir. Also we can set permission for it.
Value Permission
0 cannot read, write or execute
1 can only execute
2 can only write
3 can write and execute
4 can only read
5 can read and execute
6 can read and write
7 can read, write and execute
<?PHP
// Making a directory with the provision
// of all permissions to the owner and
// the owner's user group
mkdir("/documents/post/", 0770, true)
?>
As a complement to current solutions, a utility function.
function createDir($path, $mode = 0777, $recursive = true) {
if(file_exists($path)) return true;
return mkdir($path, $mode, $recursive);
}
createDir('path/to/directory');
It returns true if already exists or successfully created. Else it returns false.
We should always modularise our code and I've written the same check it below...
We first check the directory. If the directory is absent, we create the directory.
$boolDirPresents = $this->CheckDir($DirectoryName);
if (!$boolDirPresents) {
$boolCreateDirectory = $this->CreateDirectory($DirectoryName);
if ($boolCreateDirectory) {
echo "Created successfully";
}
}
function CheckDir($DirName) {
if (file_exists($DirName)) {
echo "Dir Exists<br>";
return true;
} else {
echo "Dir Not Absent<br>";
return false;
}
}
function CreateDirectory($DirName) {
if (mkdir($DirName, 0777)) {
return true;
} else {
return false;
}
}
You first need to check if directory exists file_exists('path_to_directory')
Then use mkdir(path_to_directory) to create a directory
mkdir( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool
More about mkdir() here
Full code here:
$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
mkdir($structure);
}
I have an array that lists folders in a directory. Until now, I've been hardcoding the folder names, but rather than do that, I thought I could easily create a script to parse the directory and just assign each folder name to the array. That way, I could easily add folders and not have to touch the script again...
The subject array creates an options list pulldown menu listing each folder...
Currently, the array is hardcoded like so...
"options" => array("folder one" => "folder1", "folder two" => "folder2")),
But I'm trying to make it dynamic based on whatever folders it finds in the given directory.
Here's the script I'm using to parse the directory and return the foldernames to the array. It works fine.
function getDirectory( $path = '.', $level = 0 )
{
// Directories to ignore when listing output.
$ignore = array( '.', '..' );
// Open the directory to the handle $dh
$dh = #opendir( $path );
// Loop through the directory
while( false !== ( $file = readdir( $dh ) ) )
{
// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) )
{
// Show directories only
if(is_dir( "$path/$file" ) )
{
// Re-call this same function but on a new directory.
// this is what makes function recursive.
//echo $file." => ".$file. ", ";
// need to return the folders in the form expected by the array. Probably could just add the items directly to the array?
$mydir2=$mydir2.'"'.$file.'" => "'.$file. '", ';
getDirectory( "$path/$file", ($level+1) );
}
}
}
return $mydir2;
// Close the directory handle
closedir( $dh );
}
And here's my first take at getting those folders into the array...
$mydir = getDirectory('/images/');
"options" => array($mydir)),
But obviously, that doesn't work correctly since its not feeding the array properly I just get a string in my options list... I'm sure this is an easy conversion step I'm missing...
Why not just look at php.net? It has several examples on recursive dir listing.
Here is one example:
<?php
public static function getTreeFolders($sRootPath = UPLOAD_PATH_PROJECT, $iDepth = 0) {
$iDepth++;
$aDirs = array();
$oDir = dir($sRootPath);
while(($sDir = $oDir->read()) !== false) {
if($sDir != '.' && $sDir != '..' && is_dir($sRootPath.$sDir)) {
$aDirs[$iDepth]['sName'][] = $sDir;
$aDirs[$iDepth]['aSub'][] = self::getTreeFolders($sRootPath.$sDir.'/',$iDepth);
}
}
$oDir->close();
return empty($aDirs) ? false : $aDirs;
}
?>
You want to create an array, not a string.
// Replace
$mydir2=$mydir2.'"'.$file.'" => "'.$file. '", ';
// With
$mydir2[$file] = $file;
Also, close $dh before returning. Now, closedir is never called.
Here is a simple function that will return an array of available directories, but it is not recursive in that it has a limited depth. I like it because it is so simple:
<?php
function get_dirs( $path = '.' ){
return glob(
'{' .
$path . '/*,' . # Current Dir
$path . '/*/*,' . # One Level Down
$path . '/*/*/*' . # Two Levels Down, etc.
'}', GLOB_BRACE + GLOB_ONLYDIR );
}
?>
You can use it like this:
$dirs = get_dirs( WP_CONTENT_DIR . 'themes/clickbump_wp2/images' );
If you're using PHP5+ you might like scandir(), which is a built-in function that seems to do pretty much what you're after. Note that it lists all the entries in a folder - files, folders, . and .. included.