针对您关于WordPress的具体问题,可以使用以下代码:
if (!is_dir(ABSPATH . 'wp-content/uploads')) wp_mkdir_p(ABSPATH . 'wp-content/uploads');
函数参考:WordPress wp_mkdir_p。 ABSPATH 是一个常量,返回 WordPress 工作目录路径。
另外还有一个 WordPress 函数叫做wp_upload_dir()
。它返回上传目录路径,并在不存在时创建文件夹。
$upload_path = wp_upload_dir();
if (!is_dir('path/to/directory')) mkdir('path/to/directory', 0777, true);
函数参考:PHP is_dir()
考虑问题的环境:
引用自:mkdir
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive= FALSE [, resource $context ]]] )
手册中指出,唯一必需的参数是$pathname
!
因此,我们可以简单编写如下代码:
<?php
error_reporting(0);
if(!mkdir('wp-content/uploads')){
// Todo
}
?>
我们不需要传递任何参数或检查文件夹是否存在,也不需要传递模式参数,除非需要考虑以下原因:
mode
在运行PHP的Windows托管环境中被忽略。mkdir
命令内置了一个检查器,用于检查文件夹是否存在; 因此,我们只需要检查返回值True|False; 它不是错误,只是警告,并且警告在托管服务器上默认禁用。这只是另一种看待问题的方式,并不声称是更好或最优解决方案。
它在PHP 7、生产服务器和Linux上进行了测试。
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);
file_exists
与is_dir
的问题,我建议你看看这里。
我尝试过了,它只会在目录不存在时创建该目录。它不关心是否有同名的文件。/* 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/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'));
}
}
if (!is_dir('path_directory')) {
@mkdir('path_directory');
}
mkdir
命令创建文件夹。同时,我们还可以为其设置权限。
Value Permission 0 cannot read, write or execute 1 can only execute 2 can only write 3 can write and execute 4 can only read 5 can read and execute 6 can read and write 7 can read, write and execute
<?PHP
// Making a directory with the provision
// of all permissions to the owner and
// the owner's user group
mkdir("/documents/post/", 0770, true)
?>
function createDir($path, $mode = 0777, $recursive = true) {
if(file_exists($path)) return true;
return mkdir($path, $mode, $recursive);
}
createDir('path/to/directory');
如果已经存在或成功创建,它返回 true
。否则,返回 false。
我们应该始终将代码模块化,我已经编写了相同的代码,请查看以下内容...
我们首先检查目录。如果目录不存在,我们就创建该目录。
$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;
}
}