Table of Contents
1. Use new methods in PHP5
2. Write your own recursive method to create multi-level directories.
The first type (use mkdirs to generate multi-level parents)
Second type
Summary:
Home Backend Development PHP Tutorial php mkdir and mkdirs operations on directories_PHP tutorial

php mkdir and mkdirs operations on directories_PHP tutorial

Jul 13, 2016 am 10:42 AM
mkdir Table of contents

How to use mkdir to create multi-level directories in PHP

2012-09-09 17:50:58| Category: Default category

function mkdirs($dir)
{
if(!is_dir($dir))
{
if(!$this->mkdirs(dirname($dir))){
return false;
}
if(!mkdir($dir,0777)){
return false;
}
}
chmod($dir, 777); //Give directory operation permissions
return true;
}

At the beginning, I thought that mkdir can create a folder as long as a path is given, but that is not the case. A single mkdir can only create one-level directories, but not multi-level ones.

So how to use mkdir to create it? First, let me copy a description of mkdir from the manual, as follows:

bool mkdir ( string pathname [, int mode [, bool recursive [, resource context]]] )


Try to create a new directory specified by pathname.

Note that you may want to specify the mode as an octal number, which means that the number should start with zero. The mode is also modified by the current umask, which can be changed with umask().


Note: mode is ignored under Windows. Optional since PHP 4.2.0.

The default mode is 0777, which means maximum possible access. For more information about mode please read the chmod() page. Example 1. mkdir() example

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


Returns TRUE on success, FALSE on failure.

Note: Since PHP 5.0.0 rmdir() can also be used with certain URL wrapping protocols. See Appendix N for a list of which URL encapsulation protocols rmdir() supports.
Note: Support for context was added in PHP 5.0.0. For a description of context, see Reference CLX, Stream Functions.
Note: The recursive parameter was added in PHP 5.0.0.
Note: When safe mode is activated, PHP will check whether the directory being manipulated has the same UID (owner) as the script being executed.

The above is the description information in the PHP5 manual, that is, you can create a folder like this: mkdir('./test',0777). But how to create multi-level directories recursively?

The methods are:

1. Use new methods in PHP5

The directory creation function mkdir under PHP5 adds a new parameter recursive. By setting recursive to true, the purpose of recursively creating a directory can be achieved, but this does not work for PHP4.

2. Write your own recursive method to create multi-level directories.

Here, I will give a little explanation on the second method. There are two methods, as follows:

The first type (use mkdirs to generate multi-level parents)

php mkdir and mkdirs operations on directories_PHP tutorial
function mkdirs($dir, $mode = 0777)

{

if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;

if (!mkdirs(dirname($dir), $mode)) return FALSE;

return @mkdir($dir, $mode);

}
Copy after login
php mkdir and mkdirs operations on directories_PHP tutorial

Description:

1. First, let’s briefly talk about the difference between mkdir() and mkdirs(), as well as is_dir and dirname():

mkdir() can only create folders in existing directories (that is, the parent must exist).
mkdirs() can create folders in non-existing directories. For example: a\b, you can create multi-level directories.

dirname() returns the directory portion of the path.

is_dir() is used to determine whether the given file name is a valid directory

2. The general process is:
(1) First use is_dir to determine whether it is already a folder, and if so, return TRUE. If it doesn't exist (or it's not a folder), try to create it. Of course, the parent may not exist, then mkdir will not be created successfully, but it will not report an error, so use @ to suppress non-fatal errors.

(2) If none of the passed parameters meet the conditions, then enter the second if statement. First, obtain the directory part of the path. Of course, it may be a multi-level parent that does not exist, so mkdirs() is used to create the parent first. level, if successful (returns FALSE if unsuccessful), then use mkdir to create the final directory.

Okay, the above is the first option.

Second type

(Note: This solution is quite streamlined, and it is a very good solution. It is recommended to use it)

function create_folders($dir){ 
return is_dir($dir) or (create_folders(dirname($dir)) and mkdir($dir, 0777)); 
}
Copy after login

Description:

General process: After getting the path, first determine whether it is a valid file directory, if so, return and end the program. If not, (because OR is used as the selective condition here, that is, as long as one of the conditions is met), it will call itself recursively, and there will be one less directory in the passed in path. In this way, first go back to the parent directory of the upper level, and then use mkdir to create the next level.

Okay, the above is how to create folders (and multi-level folders) using PHP. ^_^

Summary:

1. Use a new parameter recursive in mkdir that comes with PHP5. By setting recursive to true, you can achieve the purpose of recursively creating directories, but this will not work for PHP4.

2. In the method written by myself, use mkdirs to create multi-level parent directories

3. You can still use mkdir to create multi-level folders very cleverly.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/635024.htmlTechArticleHow to use mkdir to create multi-level directories in PHP2012-09-09 17:50:58| Category: Default Classification function mkdirs($dir) { if(!is_dir($dir)) { if(!$this->mkdirs(dirname($dir))){ return false...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
How to insert a table of contents in Google Docs How to insert a table of contents in Google Docs Apr 13, 2023 pm 08:16 PM

Whether it is an article, paper or tutorial, the main highlight of any document is the title and of course the table of contents. It describes the outline structure of the document so that users can get to where and what they expect to read from the document. It's also a best practice to add a table of contents to most documents to make them look more professional. Today, everything happens online and people use Google Docs to create most documents. Many users are still not sure how to insert or add a table of contents in google docs. Therefore, we come up with this article to explain how to create or insert a table of contents in Google Docs. How to Insert a Table of Contents in Google Docs Step 1: Click here to visit Google Docs Online. Step 2: If

Use java's File.isDirectory() function to determine whether the file exists and is a directory type Use java's File.isDirectory() function to determine whether the file exists and is a directory type Jul 24, 2023 pm 06:57 PM

Use Java's File.isDirectory() function to determine whether a file exists and is of directory type. In Java programming, you often encounter situations where you need to determine whether a file exists and is of directory type. Java provides the File class to operate files and directories. The isDirectory() function can help us determine whether a file is a directory type. The File.isDirectory() function is a method in the File class. Its function is to determine the current File

PHP function introduction—rename(): Rename a file or directory PHP function introduction—rename(): Rename a file or directory Jul 25, 2023 pm 12:10 PM

PHP function introduction—rename(): Renaming files or directories Introduction: In PHP, the rename() function is used to rename files or directories. It provides an easy way to change the name of a file or directory. Whether it is a single file or an entire directory, you can use this function to perform a rename operation. The renaming process can be easily accomplished by specifying the name of the source file or directory and the target name. Syntax: boolrename(string$source,str

How to check if a directory is empty in Linux How to check if a directory is empty in Linux Mar 20, 2023 am 10:17 AM

How to check whether the directory is empty in Linux: 1. Enter the Linux terminal; 2. By executing "res=`ls -A $dir` if [ -z $res ]; then echo "$dir ..."else echo "$ The dir..."fi" method can determine whether the directory is empty.

The glob() function in PHP is used to find files or directories The glob() function in PHP is used to find files or directories Nov 18, 2023 pm 06:17 PM

The glob() function in PHP is used to find files or directories and is a powerful file operation function. It can return the path of a file or directory based on a specified pattern match. The syntax of the glob() function is as follows: glob(pattern, flags) where pattern represents the pattern string to be matched, which can be a wildcard expression, such as *.txt (matching files ending with .txt), or a specific file path. flags is an optional parameter used to control the function

How to read the catalog when reading on WeChat How to view the catalog How to read the catalog when reading on WeChat How to view the catalog Mar 30, 2024 pm 05:56 PM

The mobile version of WeChat Reading App is a very good reading software. This software provides a lot of books. You can read them anytime, anywhere with just one click to search and read them online. All of them are officially authorized and different types of books are neatly arranged. Sort and enjoy a comfortable and relaxing reading atmosphere. Switch the reading modes of different scenarios, update the latest book chapters continuously every day, support online login from multiple devices, and batch download to the bookshelf. You can read it with or without the Internet, so that everyone can discover more knowledge from it. Now the editor details it online Promote the method of viewing the catalog for WeChat reading partners. 1. Open the book you want to view the catalog and click in the middle of the book. 2. Click the three lines icon in the lower left corner. 3. In the pop-up window, view the book catalog

Get the directory portion of a file path using the path/filepath.Dir function Get the directory portion of a file path using the path/filepath.Dir function Jul 27, 2023 am 09:06 AM

Use the path/filepath.Dir function to obtain the directory part of the file path. In our daily development process, file path processing is often involved. Sometimes, we need to get the directory part of the file path, that is, the path to the folder where the file is located. In the Go language, you can use the Dir function provided by the path/filepath package to implement this function. The signature of the Dir function is as follows: funcDir(pathstring)string The Dir function receives a word

A complete list of Linux system commands. A complete list of Linux system commands. Feb 19, 2024 pm 10:54 PM

The following is a list of common Linux system commands (arranged in alphabetical order): alias: set command alias awk: text processing tool, used to extract and manipulate text data cat: connect files and print to standard output cd: change the current working directory chmod: Modify the permissions of a file or directory chown: Modify the owner and group of a file or directory chroot: Change the root file system directory cp: Copy a file or directory cron: A scheduled task management tool curl: A command line tool for downloading or uploading files cut :Extract text data by columns date:Display or set the system date and time dd:Copy and convert files df:Display the disk usage of the file system diff:Compare files or destinations

See all articles