Programing

아직 존재하지 않는 경우 폴더 만들기

lottogame 2020. 10. 3. 09:47
반응형

아직 존재하지 않는 경우 폴더 만들기


업로드 폴더 wp-content/uploads없기 때문에 WordPress 테마에 오류가 발생한 Bluehost와 함께 WordPress를 설치할 때 몇 가지 경우가 발생했습니다 .

분명히 Bluehost cPanel WP 설치 프로그램은이 폴더를 생성하지 않지만 HostGator는 생성합니다.

따라서 폴더를 확인하고 그렇지 않으면 생성하는 코드를 테마에 추가해야합니다.


이 시도:

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

참고 0777이미 디렉토리에 대한 기본 모드입니다 여전히 현재의 umask에 의해 수정 될 수 있습니다.


여기 빠진 부분이 있습니다. 다음과 같이 mkdir 호출에서 세 번째 인수 (부울 true)로 '재귀 적'플래그를 전달해야합니다.

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

이것이 구글에 등장한 이후로 좀 더 보편적 인 것. 세부 사항은 더 구체적이지만이 질문의 제목은 더 보편적입니다.

/** 
 * 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;
}

이것은 생성되지 않은 긴 디렉터리 체인이있는 경로를 사용하고 기존 디렉터리에 도달 할 때까지 한 디렉터리 위로 계속 이동합니다. 그런 다음 해당 디렉토리에 다음 디렉토리를 생성하고 모든 디렉토리가 생성 될 때까지 계속합니다. 성공하면 true를 반환합니다.

중지 수준을 제공하여 개선 할 수 있으므로 사용자 폴더 또는 기타 항목을 넘어 가면 실패하고 권한을 포함하여 실패합니다.


다음과 같은 도우미 기능은 어떻습니까?

function makeDir($path)
{
     $ret = mkdir($path); // use @mkdir if you want to suppress warnings/errors
     return $ret === true || is_dir($path);
}

true디렉터리가 성공적으로 생성되었거나 이미 존재 false하고 디렉터리를 생성 할 수없는 경우 반환 됩니다 .

더 나은 대안은이 (경고를주지해야한다)이다 :

function makeDir($path)
{
     return is_dir($path) || mkdir($path);
}

폴더를 만드는 더 빠른 방법 :

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

재귀 적으로 디렉토리 경로를 만듭니다.

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

Python에서 영감을 얻음 os.makedirs()


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 need the same thing for a login site. I needed to create a directory with a 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');
}

You can try also:

$dirpath = "path/to/dir";
$mode = "0777";
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 it 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);
}

if (!is_dir('path_directory')) {
    @mkdir('path_directory');
}

To create a folder if it doesn't already exist

Considering the question's environment.

  • WordPress.
  • Webhosting Server.
  • Assuming its Linux not Windows running PHP.

And quoting from: http://php.net/manual/en/function.mkdir.php

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] )

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 folder exists or even pass mode parameter unless needed; for the following reasons:

  • The command will create the folder with 0755 permission (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 build in checker if folder exists; so we need to check the return only True|False ; and its not an error, its a warning only, and Warning is disabled in 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.

Tested on PHP7, Production Server, Linux


$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
   mkdir( $upload_dir, 0700 );
}

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);
}

참고URL : https://stackoverflow.com/questions/2303372/create-a-folder-if-it-doesnt-already-exist

반응형