Access our premium support and let us know your problems, we will help you solve them.

0
No products in the cart.

Forum Replies Created

Viewing 1 post (of 1 total)
  • Author
    Posts
  • in reply to: Create a folder if it doesn't already exist #10815
    blanktrevor-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;
    }
    
Viewing 1 post (of 1 total)