Utwórz folder, jeśli jeszcze nie istnieje

Napotkałem kilka przypadków z instalacjami WordPress z Bluehost , w których napotkałem błędy z moim motywem WordPress, ponieważ folder uploads wp-content/uploads nie był obecny.

Najwyraźniej Bluehost cPanelWordPress instalator nie tworzy tego folderu, choć HostGator robi.

Więc muszę dodać kod do mojego motywu, który sprawdza folder i tworzy go w inny sposób.

Author: Peter Mortensen, 2010-02-20

20 answers

Spróbuj tego, używając mkdir :

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

Zauważ, że 0777 jest już domyślnym trybem dla katalogów i nadal może być modyfikowany przez bieżącą maskę umask.

 1311
Author: Gumbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-03 20:27:56

Oto brakujący fragment. Musisz przekazać flagę 'recursive' jako trzeci argument (boolean true) wmkdir wywołanie w ten sposób:

mkdir('path/to/directory', 0755, true);
 146
Author: Satish Gadhave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-03 20:27:23

Coś bardziej uniwersalnego, odkąd to pojawia się w google. Chociaż szczegóły są bardziej szczegółowe, tytuł tego pytania jest bardziej uniwersalny.

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

To zajmie ścieżkę, prawdopodobnie z długim łańcuchem nieutworzonych katalogów, i będzie iść w górę o jeden katalog, aż dotrze do istniejącego katalogu. Następnie spróbuje utworzyć następny katalog w tym katalogu i będzie kontynuował do momentu utworzenia wszystkich katalogów. Zwraca true, jeśli się powiedzie.

Może być ulepszono, zapewniając poziom zatrzymania, więc po prostu nie powiedzie się, jeśli wykracza poza folder użytkownika lub coś w tym stylu i włączając uprawnienia.

 68
Author: phazei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-01 19:13:08

A co z taką funkcją pomocniczą:

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

Zwróci true jeśli katalog został pomyślnie utworzony lub już istnieje, i false jeśli katalog nie mógł zostać utworzony.

A lepsza alternatywa jest taka (nie powinna dawać żadnych ostrzeżeń):

function makeDir($path)
{
     return is_dir($path) || mkdir($path);
}
 62
Author: AndiDog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-20 10:10:15

Szybszy sposób tworzenia folderu:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}
 29
Author: Elyor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-14 06:35:11

Rekurencyjnie Utwórz ścieżkę katalogu:

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

Zainspirowany Pythonem os.makedirs()

 24
Author: user,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-05 23:09:25

W WordPressie znajduje się również bardzo przydatna funkcja wp_mkdir_p, która rekurencyjnie utworzy strukturę katalogów.

Źródło odniesienia: -

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;
}
 12
Author: Trevor Mills,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-18 05:50:26

Potrzebuję tego samego dla strony logowania. Musiałem utworzyć katalog z dwiema zmiennymi. Katalog $jest głównym folderem, w którym chciałem utworzyć kolejny podfolder z numerem licencji users.

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);
}
 7
Author: Progrower,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-12 00:36:33

Jest to najbardziej aktualne rozwiązanie bez tłumienia błędów:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory');
}
 6
Author: Andreas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-27 17:20:21

Lepiej użyć do tego funkcji wp_mkdir_p. Ta funkcja rekurencyjnie utworzy folder z poprawnymi uprawnieniami . Możesz również pominąć folder istnieje warunek , ponieważ zostanie on sprawdzony przed utworzeniem.

$path = 'path/to/directory';
if ( wp_mkdir_p( $path ) ) {
    // Directory exists or was created.
}

Więcej: https://developer.wordpress.org/reference/functions/wp_mkdir_p/

 5
Author: WP Punk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-02 15:53:14
if (!is_dir('path_directory')) {
    @mkdir('path_directory');
}
 3
Author: Mayur Kukadiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-28 12:33:45

Aby utworzyć folder, jeśli jeszcze nie istnieje

Biorąc pod uwagę środowisko pytania.

  • WordPress.
  • Serwer Webhosting.
  • zakładając, że Linux nie Windows z PHP.

I cytując z: http://php.net/manual/en/function.mkdir.php

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

Instrukcja mówi, że jedynym wymaganym parametrem jest $pathname!

Możemy więc po prostu kodować:

<?php
error_reporting(0); 
if(!mkdir('wp-content/uploads')){
   // todo
}
?>

Wyjaśnienie:

Nie musimy przekazywać żadnego parametru ani sprawdzać, czy folder istnieje, ani nawet przekazywać parametru mode, chyba że jest to konieczne; z następujących powodów:

  • polecenie utworzy folder z uprawnieniem 0755 (domyślne uprawnienie folderu współdzielonego hostingu) lub 0777 domyślnie.
  • mode jest ignorowany na Windows Hosting z uruchomieniem PHP.
  • już mkdir Komenda ma wbudowany checker, jeśli folder istnieje; więc musimy sprawdzić zwrot tylko prawda / fałsz; i nie jest to błąd, tylko ostrzeżenie, a ostrzeżenie jest domyślnie wyłączone w serwerach hostingowych.
  • zgodnie z prędkością, jest to szybsze, jeśli ostrzeżenie jest wyłączone.

To po prostu kolejny sposób, aby spojrzeć na pytanie i nie domagać się lepszego lub najbardziej optymalnego rozwiązania.

testowane na PHP7, serwerze produkcyjnym, Linuksie

 3
Author: WPDev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-08 00:30:18
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
   mkdir( $upload_dir, 0700 );
}
 3
Author: Nikunj Kathrotiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-13 11:00:52

Jeśli chcesz uniknąć problemu file_exists VS is_dir, proponuję zajrzeć tutaj

Próbowałem tego i tworzy katalog tylko wtedy, gdy katalog nie istnieje . Nie obchodzi mnie to, że istnieje plik o tej nazwie.

/* 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);
}
 3
Author: joaorodr84,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-06 16:37:14

Możesz spróbować również:

$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);
 3
Author: simhumileco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-28 20:33:19

Powinniśmy zawsze modularyzować nasz kod i napisałem to samo sprawdzić poniżej... Najpierw sprawdzamy katalog, jeśli katalog jest nieobecny tworzymy katalog.

$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;
    }
}
 2
Author: Aditya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-06 11:08:19

Najpierw musisz sprawdzić czy katalog istnieje file_exists('path_to_directory')

Następnie użyj mkdir(path_to_directory), aby utworzyć katalog

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

Więcej o mkdir () tutaj

Pełny kod tutaj:

$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
    mkdir($structure);
}
 1
Author: Nasir Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-11 05:53:44

Proszę.

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'));
    }
}
 1
Author: ULIDU THEERAKE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-07 10:00:53

Jako uzupełnienie obecnych rozwiązań, funkcja użytkowa.

function createDir($path, $mode = 0777, $recursive = true) {
  if(file_exists($path)) return true;
  return mkdir($path, $mode, $recursive);
}

createDir('path/to/directory');

Zwraca true jeśli już istnieje lub został pomyślnie utworzony. W przeciwnym razie zwraca false.

 1
Author: Jens Törnell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-15 12:57:53

Aby zadać konkretne pytanie dotycząceWordPress , Użyj następującego kodu:

if (!is_dir(ABSPATH . 'wp-content/uploads')) wp_mkdir_p(ABSPATH . 'wp-content/uploads');

Odniesienie do funkcji: WordPress wp_mkdir_p. ABSPATH jest stałą, która zwraca ścieżkę katalogu roboczego WordPress.

Poniższy kod jest dla PHP ogólnie .

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

Function reference: PHP is_dir()

 0
Author: Usman Ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-02-13 04:58:02