Home Backend Development PHP Tutorial PHP recursively creates directories (pseudo-original)_PHP tutorial

PHP recursively creates directories (pseudo-original)_PHP tutorial

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

Sometimes you need to create a directory function recursively. In this case, you need to use the dirname() function (to obtain the directory part of the path) and the mkdir() function (to create the directory).

Let’s popularize the grammar first:

dirname

(PHP 4, PHP 5)

dirname — Returns the directory portion of the path

Description ?

string dirname ( string $path )

Given a string containing the full path to a file, this function returns the directory name after removing the file name.

Parameter ?

path

A path.

In Windows, both slash (/) and backslash () can be used as directory separators. In other circumstances it is a slash (/).

Return value ?

Returns the parent directory of path. If there are no slashes in path, a dot ('.') is returned, indicating the current directory. Otherwise, the string returned is the string after removing the /component at the end of path (the last slash and the following part).

Update log ?

版本 说明
5.0.0 dirname() 的操作从 PHP 5.0.0 版开始是二进制安全的。
4.0.3 在这个版本中,dirname() 被修正为 POSIX 兼容。

Example ?

Example #1 dirname() Example

<?php <br> echo "1) " . dirname("/etc/passwd") . PHP_EOL; // 1) /etc<br> echo "2) " . dirname("/etc/") . PHP_EOL; // 2) / (or on Windows)<br> echo "3) " . dirname("."); // 3) .<br> ?>

Comment ?

Note:

dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Note:

dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function.

Note:

Since PHP 4.3.0, you will often get a slash or a dot back from dirname() in situations where the older functionality would have given you the empty string.

Check below an example of what happened:

<?php <br> <br> // PHP 4.3.0 以前<br> dirname('c:/'); // 返回 '.'<br> <br> // PHP 4.3.0 以后<br> dirname('c:/x'); // 返回 'c:'<br> dirname('c:/Temp/x'); // 返回 'c:/Temp'<br> dirname('/x'); // 返回 '/' (or '' on Windows)<br> <br> ?>

See ?

  • basename() - Return the file name part of the path
  • pathinfo() - Returns file path information
  • realpath() - Returns the normalized absolute pathname


    mkdir

    (PHP 4, PHP 5)

    mkdir — Create a new directory

    Description ?

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

    Try to create a new directory specified by pathname.

    Parameter ?

    pathname

    The path to the directory.

    mode

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

    Note:

    mode in Ignored under Windows.

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

    recursive

    Allows the creation of nested directories specified in the pathname.

    context

    Note: Support for Context was added in PHP 5.0.0. See Streams for a description of context.

    Return value ?

    Returns TRUE on success, or FALSE on failure.

    Update log ?

    Version Description
    5.0.0 Add
    版本 说明
    5.0.0 添加 recursive 参数。
    5.0.0 mkdir() 也可用于某些 URL 封装协议。参见支持的协议和封装协议 的列表看看 mkdir() 支持哪些 URL 封装协议。
    4.2.0 mode 成为可选项。
    parameter.
    5.0.0 mkdir() also works with certain URLs Encapsulation protocol. See the list of supported protocols and encapsulated protocols to see what mkdir() supports. URL encapsulation protocol.
    4.2.0 becomes optional.

    Example ?

    Example #1 mkdir() Example

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

    Example #2 Using mkdir()recursive with

    parameter <?php <br> // Desired folder structure<br> $structure = './depth1/depth2/depth3/';<br> <br> // To create the nested structure, the $recursive parameter <br> // to mkdir() must be specified.<br> <br> if (!mkdir($structure, 0, true)) {<br> die('Failed to create folders...');<br> }<br> <br> // ...<br> ?>

    Comment ?

    Note: When safe mode is enabled, PHP will check when executing a script whether the directory being scripted has the same UID (owner) as the script being executed.

    See ?

    • is_dir() - Determine whether the given file name is a directory
    • rmdir() - delete directory

      Recursively create directory function:

      /**
      	 * Create the directory recursively.
      	 * @param $path The directory to create, such as, /a/b/c/d/e/
      	 * @param $mode The mode of the directory to create, such as, 0755, 0777.
      	 */
      	function RecursiveMkdir($path,$mode) {
      		
      		if (!file_exists($path)) { // The file is not exist.
      			RecursiveMkdir(dirname($path), $mode); // Call itself.
      			if(mkdir($path, $mode)) { // Call mkdir() to create the last directory, and the result is true.
      				return true; 
      			} else { // Call mkdir() to create the last directory, and the result is false.
      				return false;
      		   }
             } else { // The file is already exist.
      		   return true;
      	   }
         }
      Copy after login



      References:

      Click to open link Click to open link
      Click to open link

      www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/664278.htmlTechArticleSometimes you need to create a directory function recursively. In this case, you need to use the dirname() function (get the directory part of the path) and mkdir() function (create directory). Let’s popularize the grammar first: dirnam...
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 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)

Recursive implementation of C++ functions: Is there a limit to recursion depth? Recursive implementation of C++ functions: Is there a limit to recursion depth? Apr 23, 2024 am 09:30 AM

The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

Do C++ lambda expressions support recursion? Do C++ lambda expressions support recursion? Apr 17, 2024 pm 09:06 PM

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

How to create a folder on Realme Phone? How to create a folder on Realme Phone? Mar 23, 2024 pm 02:30 PM

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Apr 22, 2024 pm 03:18 PM

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application Apr 30, 2024 am 10:45 AM

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.

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

Detailed explanation of C++ function recursion: tail recursion optimization Detailed explanation of C++ function recursion: tail recursion optimization May 03, 2024 pm 04:42 PM

Recursive definition and optimization: Recursive: A function calls itself internally to solve difficult problems that can be decomposed into smaller sub-problems. Tail recursion: The function performs all calculations before making a recursive call, which can be optimized into a loop. Tail recursion optimization condition: recursive call is the last operation. The recursive call parameters are the same as the original call parameters. Practical example: Calculate factorial: The auxiliary function factorial_helper implements tail recursion optimization, eliminates the call stack, and improves efficiency. Calculate Fibonacci numbers: The tail recursive function fibonacci_helper uses optimization to efficiently calculate Fibonacci numbers.

See all articles