How to Create a folder if it doesn’t already exist ?

How to Create a folder if it doesn’t already exist ?

Asked on October 24, 2018 in Wordpress.
Add Comment


  • 4 Answer(s)

    Use this code:

    if (!file_exists('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
    }
    

    That the 0777 would be the default mode for the directories would be still modified by the current umask.

    Answered on October 24, 2018.
    Add Comment

    We need to pass the ‘recursive’ flag as the third argument (boolean true) in mkdir call :

    mkdir('path/to/directory', 0755, true);
    
    

    The code can be used to Create a folder if it doesn’t already exist.

    Answered on October 24, 2018.
    Add Comment

    Try this:

    /**
    * 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;
    }
    
    Answered on October 24, 2018.
    Add Comment
    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.

    better alternative is this (shouldn’t give any warnings):

    function makeDir($path)
    {
         return is_dir($path) || mkdir($path);
    }
    Answered on February 20, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.