mkdir

(PHP 4, PHP 5, PHP 7, PHP 8)

mkdir新建目录

说明

mkdir(
    string $pathname,
    int $mode = 0777,
    bool $recursive = false,
    resource $context = ?
): bool

尝试新建一个由 pathname 指定的目录。

参数

pathname

目录的路径。

mode

默认的 mode 是 0777,意味着最大可能的访问权。有关 mode 的更多信息请阅读 chmod() 页面。

注意:

mode 在 Windows 下被忽略。

注意也许想用八进制数指定模式,也就是说该数应以零打头。模式也会被当前的 umask 修改,可以用 umask() 来改变。

recursive

允许递归创建由 pathname 所指定的多级嵌套目录。

context

上下文流(context stream) resource

返回值

成功时返回 true, 或者在失败时返回 false

范例

示例 #1 mkdir() 例子

<?php
mkdir
("/path/to/my/dir"0700);
?>

示例 #2 通过 recursive 参数使用 mkdir()

<?php
// Desired folder structure
$structure './depth1/depth2/depth3/';

// To create the nested structure, the $recursive parameter 
// to mkdir() must be specified.

if (!mkdir($structure0777true)) {
    die(
'Failed to create folders...');
}

// ...
?>

错误/异常

目录已存在时,产生 E_WARNING错误。

如果因为权限问题无法创建目录,导致 E_WARNING错误。

参见

  • is_dir() - 判断给定文件名是否是一个目录
  • rmdir() - 删除目录

add a note

User Contributed Notes 4 notes

up
29
jack dot sleight at gmail dot com
12 years ago
When using the recursive parameter bear in mind that if you're using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie:

<?php
mkdir
('/test1/test2', 0777, true);
chmod('/test1/test2', 0777);
?>

May result in "/test1/test2" having a mode of 0777 but "/test1" still having a mode of 0755 from the mkdir() call. You'd need to do:

<?php
mkdir
('/test1/test2', 0777, true);
chmod('/test1', 0777);
chmod('/test1/test2', 0777);
?>
up
13
aulbach at unter dot franken dot de
23 years ago
This is an annotation from Stig Bakken:

The mode on your directory is affected by your current umask.  It will end
up having (<mkdir-mode> and (not <umask>)).  If you want to create one
that is publicly readable, do something like this:

<?php
$oldumask
= umask(0);
mkdir('mydir', 0777); // or even 01777 so you get the sticky bit set
umask($oldumask);
?>
up
4
Protik Mukherjee
17 years ago
mkdir, file rw, permission related notes for Fedora 3////
If you are using Fedora 3 and are facing permission problems, better check if SElinux is enabled on ur system. It add an additional layer of security and as a result PHP cant write to the folder eventhough it has 777 permissions. It took me almost a week to deal with this!

If you are not sure google for SElinux or 'disabling SELinux' and it may be the cure! Best of luck!
up
2
julius - grantzau - c-o-m
11 years ago
Remember to use clearstatcache()

... when working with filesystem functions.

Otherwise, as an example, you can get an error creating a folder (using mkdir) just after deleting it (using rmdir).
To Top