[Special Summer Sale] 40% OFF All Magento 2 Themes

Cart

Create a folder if it doesn't already exist

  • This topic is empty.
Viewing 15 posts - 1 through 15 (of 22 total)
  • Author
    Posts
  • #10801
    scott-b
    Participant

    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.

    #10822
    gumbo
    Participant

    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.

    #10820
    andidog
    Participant

    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);
    }
    
    #10819
    phazei
    Participant

    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.

    #10821
    satish-gadhave
    Participant

    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);
    
    #10806
    mayur-kukadiya
    Participant
    if (!is_dir('path_directory')) {
        @mkdir('path_directory');
    }
    
    #10814
    progrower
    Participant

    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);
    }
    
    #10815
    trevor-mills
    Participant

    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;
    }
    
    #10817
    user
    Participant

    Recursively create the directory path:

    function makedirs($dirpath, $mode=0777) {
        return is_dir($dirpath) || mkdir($dirpath, $mode, true);
    }
    

    Inspired by Python’s os.makedirs()

    #10813
    andreas
    Participant

    This is the most up-to-date solution without error suppression:

    if (!is_dir('path/to/directory')) {
        mkdir('path/to/directory');
    }
    
    #10807
    simhumileco
    Participant

    You can try also:

    $dirpath = "path/to/dir";
    $mode = "0764";
    is_dir($dirpath) || mkdir($dirpath, $mode, true);
    
    #10818
    elyor
    Participant

    A faster way to create a folder:

    if (!is_dir('path/to/directory')) {
        mkdir('path/to/directory', 0777, true);
    }
    
    #10808
    wpdev
    Participant

    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

    #10809
    nikunj-kathrotiya
    Participant
    $upload = wp_upload_dir();
    $upload_dir = $upload['basedir'];
    $upload_dir = $upload_dir . '/newfolder';
    if (! is_dir($upload_dir)) {
       mkdir( $upload_dir, 0700 );
    }
    
    #10803
    aditya-malviya
    Participant

    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;
        }
    }
    
Viewing 15 posts - 1 through 15 (of 22 total)
  • You must be logged in to reply to this topic.