search
HomeBackend DevelopmentPHP TutorialHow to create multi-level directories in php using mkdir

  1. mkdir("/path/to/my/dir", 0700);
  2. ?>
Copy code

Returns TRUE if successful and FALSE if failed.

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 one (use mkdirs to generate multi-level parents)

  1. function mkdirs($dir, $mode = 0777)
  2. {
  3. if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
  4. if ( !mkdirs(dirname($dir), $mode)) return FALSE;
  5. return @mkdir($dir, $mode);
  6. }
Copy code

Instructions: 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 it first. Parent, 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)

  1. function create_folders($dir){
  2. return is_dir($dir) or (create_folders(dirname($dir)) and mkdir($dir, 0777));
  3. }
Copy code

Instructions: 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.



Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software