24.09.2024
Home / Linux Overview / Php works - Create a folder if it doesn't already exist. Mkdir function in PHP, description and examples Php creating a folder if it does not exist

Php works - Create a folder if it doesn't already exist. Mkdir function in PHP, description and examples Php creating a folder if it does not exist

The mkdir() function creates a new folder in the specified directory. If creation is successful, returns True. When creating a new folder, you can set access rights to it using the $mode parameter. By setting $recursive to True, you can create multiple subfolders.

PHP version 4 and higher.

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

mkdir function parameters

$pathnamePath to the directory to be created.
$modeRights to the created folder. Rights are assigned as an octal value with a mandatory zero in the first place (0777). Apart from the first zero, the numbers represent access levels for the owner, for the owner's group, for everyone else.
The access level is determined by the numbers:
0 – access denied;
1 – read access;
2 – write access;
4 – execution access.
Most often, rights are specified as a composite amount, for example:
7 – full access (1+2+4);
5 – reading and execution (1+4).
The default value is 0777.
$recursiveA Boolean parameter that determines whether nested subdirectories can be created.
$contextUsed when working with streams. Added in PHP 5.0.0.

Examples of using the mkdir function

mkdir( "newfolder" );

mkdir( "../newfolder" ); // one level down

mkdir("/folder1/folder2/newfolder" ); // full path

mkdir( "newfolder" , 0777); // create a folder with assigned rights

If you need to create multiple subfolders, you need to set $recursive = True.

mkdir("folder1/folder2/newfolder" , 0777, True ); // creating a folder in the current directory


publication of this article is permitted only with a link to the website of the author of the article

In this article I will describe one option to work around the problem of creating folders with using php in safe mode.
To create a folder in PHP, there is a standard mkdir() function, but in most cases it turns out to be useless and many people know about it, but not many people know that you can work around this problem.
Everything is very simple, you need to create folders using the built-in php functions FTP.
Below I write about this in more detail.

Problems with mkdir() when creating a folder.
As you know, if enabled in php safe mode(safe_mode = on), then creating folders (directories) using mkdir() will not work. To be more precise, you can create it, but further use of this folder will be impossible. You will not be able to upload files to this folder, you will not be able to rename it and you will not be able to delete it, even if you log in via FTP (in some cases you can delete via FTP).

Safe mode is enabled by default on all servers and all hosting providers. If you don't have the option to disable Safe Mode, there is another way out.

Creating folders in php using FTP.
Almost all servers and hosting have ftp support enabled in php.
With the help of these functions we will get around the problem of creating the mkdir() folder.
An example of creating a folder via FTP.

$conn_id = @ ftp_connect ("ftp.server.ru" , 21 , 5 ); // connect to the FTP server
if($conn_id) // if the connection to the server was successful, continue
{
$login_result = @ftp_login($conn_id, "user", "pass"); // enter your login and password for FTP
if($login_result) // if the server accepted the login password, move on
{
// now you need to play with the passive mode, turn it on or off (TRUE, FALSE)
// if further ftp functions do not work correctly, try changing this parameter (TRUE or FALE)
ftp_pasv($conn_id, TRUE); // in this case passive mode is enabled
ftp_mkdir($conn_id, "1/2/3"); // and the folder creation itself
}
}
ftp_close($conn_id); // and close the FTP connection
?>
Now, not a big comment on the code.
The first line connects to the FTP server. Usually, to connect to a local FTP server, it is enough to specify localhost as the server, but you can also specify the full address.
Whether passive mode is enabled or disabled depends on the FTP settings.

When creating a folder, be careful, the folder is created from the FTP login root. That is, the paths here are different from the paths file system and the folder is created as seen through FTP.
If when creating a folder you specify several attachments, as in my example "1/2/3", then in this case all the missing folders will be created. If there is no folder "1", it will be created, and in it the folder "2" will be created, and in it the folder "3" will be created. If intermediate folders already exist, then only the missing ones will be created.
Before creating a folder, you can move to a folder, for example


And after this function you can create a folder. If the path to the folder is specified as “2/3” without the leading slash, then the folder will be created relative to the folder in which we are currently located. That is, the folder "1/2/3" will be created


If you specify a leading slash (/1/2/3) when creating a folder, the folder will be created from the FTP root, regardless of which folder you moved to.

Comments

10/14/2009 Sergey
everything ingenious is simple :)

12.12.2009 Victor
Thank you, everything works, but in the ftp client the created folders are not immediately visible, you have to restart it, i.e. don’t just disconnect from the server and connect again, but close the program and run it again (I use FileZilla Client).

12/14/2009 Admin
I think that's all FTP clients cache files and folders. For example, in Total Commander there is a special “update” button for such matters; it’s a shame that FileZilla doesn’t have this.

01/24/2010 Alexander
How come there’s no such thing in FileZilla, I have version 3.2.2, it’s already about a year old and there is such a function and as far as I remember it has always been!!!

08/27/2010 Vitaly
Folders are created with 755 on the right, but you need 777.
At the creation stage, is it possible to somehow configure with what rights the folder will be created via FTP?

08/27/2010 Admin
Vitaly, there is a function for this
ftp_chmod($conn_id, 0777, $file)
after creating a folder or file, use it

08/28/2010 Vitaly
thank you, Admin!

09/12/2010 Andrey
Excuse me, why don’t I create several directories, that is:

06/12/2011 Ilya
Something is not going well. The server issues:
Warning: ftp_close() expects parameter 1 to be resource, boolean given in /home/bos/p/h/p/phpscripts/public_html/formf.php on line 19

06/15/2011 Victor
Ilya, he writes that the first parameter you are passing to the ftp_close function is not correct

06/29/2011 Alexey
Same problem as Andrey
(multiple directories are not created)
ftp_mkdir ($conn_id, "1"); // this is how it works
but like this ftp_mkdir ($conn_id, "1/2/3"); // does not work.
???

07/27/2011 Victor
Alexey, strange, I checked, it creates several folders for me.
Maybe some tricky mode is enabled on the server, then you need to create folders one by one, first create folder 1, then enter it and create folder 2 in it, then enter folder 2 and create 3 in it...

11/07/2011 k1-801 (Dmitry is possible)
And to delete folders, as far as I understand, through
rmdir_ftp($conn_id, $dir);
So?

And, by the way, for some reason it doesn’t create a folder for me (and doesn’t write errors... strange...)

03/10/2012 YA
Thank you, otherwise I was tormented with this question.
and you forgive everything and the main thing is it works

05/29/2012 Mikhail
Of course I'm sorry. Where should I write this code, otherwise I’m not good at it at all, but I really need to create a folder))

07/04/2012 Nomaq
Something is wrong with me... the first time the code skips, the second time it says that such a folder already exists... it seems like it is being created, but it is not visible even after restarting FTP((((
and also, I need to create a folder not in the same folder where the PHP file is, but go back one step, and then enter another folder and create it there.. something like this:
../folder1/new folder here
please help, if not difficult) thank you)

07/04/2012 Nomaq
I figured out the ways))) thanks in general for the article, it’s rare that anyone explains properly what’s how)))

01/27/2013 CiliZ
Well done, respect for the article

06/05/2013 Vasily
The corporate folder is the main element corporate identity companies. It is a product for attaching a small amount of documents and paper materials. Folders are used both within a company, for storing and moving documentation, and for advertising purposes. More details on the website: www.logodesigner.ru/papki

remove tags (12)

I have encountered several cases with WordPress installations from Bluehost where I encountered errors in my WordPress theme because the uploads wp-content/uploads folder was missing.

Apparently the Bluehost cPanel WP installer does not create this folder, although HostGator does.

So I need to add code to my theme that checks for the folder and creates it otherwise.

Answers

Try this:

If (!file_exists("path/to/directory")) ( mkdir("path/to/directory", 0777, true); )

Note that 0777 is already the default mode for directories and can still be changed by the current umask.

WordPress also has a very handy function wp_mkdir_p which will recursively create a directory structure.

Source for reference:-

Function wp_mkdir_p($target) ( $wrapper = null; // strip the protocol if(wp_is_stream($target)) ( list($wrapper, $target) = explode("://", $target, 2); ) // from php.net/mkdir user contributed notes $target = str_replace("//", "/", $target); // put the wrapper back on the target if($wrapper !== null) ( $target); = $wrapper . "://" . $target; ) // safe mode fails with a trailing slash under certain PHP versions. $target = rtrim($target, "/"); to avoid formatting.php dependency. if (empty($target)) $target = "/"; if (file_exists($target)) return @is_dir($target); that exists and inherit that. $target_parent = dirname($target); while ("." != $target_parent && ! is_dir($target_parent)) ( $target_parent = dirname($target_parent); ) // Get the permission bits. if ($stat = @stat($target_parent)) ( $dir_perms = $stat["mode"] & 0007777; ) else ( $dir_perms = 0777; ) if (@mkdir($target, $dir_perms, true)) ( // If a umask is set that modifies $dir_perms, we"ll have to re-set the $dir_perms correctly with chmod() if ($dir_perms != ($dir_perms & ~umask())) ( $folder_parts = explode( "/", substr($target, strlen($target_parent) + 1)); for ($i = 1; $i<= count($folder_parts); $i++) { @chmod($target_parent . "/" . implode("/", array_slice($folder_parts, 0, $i)), $dir_perms); } } return true; } return false; }

I need the same for the login site. I needed to create a directory with two variables. The $ directory is the main folder where I wanted to create another subfolder with the users license number.

Include_once("../include/session.php"); $lnum = $session->lnum; //Users license number from sessions $directory = uploaded_labels; // Name of directory that folder is being created in if (!file_exists($directory."/".$lnum)) ( mkdir($directory."/".$lnum, 0777, true); )

Something more generic as it shows up on google. While the details are more specific, the title of this question is more generic.

/** * recursively create a long directory path */ function createPath($path) ( if (is_dir($path)) return true; $prev_path = substr($path, 0, strrpos($path, "/", - 2) + 1); $return = createPath($prev_path); return ($return && is_writable($prev_path)) ? mkdir($path) : false;

This will take a path with possibly a long chain of uncreated directories and continue moving up one directory until it ends up in an existing directory. It will then try to create the next directory within that directory and continue until all directories have been created. It returns true if successful.

Could be improved by providing a stop level so it just fails if it goes outside the user's folder or something, and enabling permissions.

To create a folder if it doesn't already exist

Consideration of the environmental issue.

  • WordPress.
  • Web hosting server.
  • Assuming Linux is not running PHP.

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

The manual states that the only required parameter is $pathname !

so we can simply code:

Explanation:

We don't need to pass any parameter or check if the folder exists or even the transfer mode parameter if needed; for the following reasons:

  • The command will create a folder with a permission of 0755 (the default permission for a public folder) or 0777, the default permission for the command.
  • mode is ignored in Windows host running PHP .
  • The mkdir command has a built-in check if the folder exists; so we only need to check for returning True | False; and this is not an error, its a warning only, and the warning is disabled on hosting servers by default.
  • Depending on the speed it is faster if the warning is disabled.

This is another way of looking at the question and not claiming the best or optimal solution.

Tested on PHP7, Production Server, Linux

You can also try:

$dirpath = "path/to/dir"; $mode = "0777"; is_dir($dirpath) || mkdir($dirpath, $mode, true);

If (!is_dir("path_directory")) ( @mkdir("path_directory"); )

A faster way to create a folder:

If (!is_dir("path/to/directory")) ( mkdir("path/to/directory", 0777, true); )

you will do

Printf("Hi %s,
", $name);

before installation cookies, which is prohibited. You cannot send any data before the headers, not even an empty line.

PHP has a single function - mkdir(), which allows you to create directories on the website server, which are sometimes so necessary in the household. For example, when creating a new material, you need to create a folder for it, where, again using your CMS, you will upload all the necessary files.

Mkdir("/path/to/my/dir", 0700);

Those. in a certain directory we create a new folder and, for example, set its mode to mode 0700, for example, in order to be able to write files to the folder, we change the mode to 0777.

But this is where the problem with mkdir() arises. When doing this php script when the safe_mode server function is enabled, the owner (UID) is checked and if the owner of the script and the folder do not match, then you may not be able, for example, to write a file to the created directory, delete a file in it, or, for example, via FTP you will not be able to delete the folder itself .

But there is a more elegant solution to this problem, without having to ask the hoster to disable the safe_mode function for you (this function is enabled on absolutely all hosting sites by default, in order to ensure security). Basically, paid hosting services also provide access to ftp, and this is what we will start from.

$conn_ftp = @ftp_connect("your_ftp_server", 21, 5);

The first variable in the function is the address of your ftp server, the second is the port on which you connect to ftp and the last is the allowed connection timeout. A little about the timeout, it is necessary for subsequent network operations; if you do not enter it, then the default value is set to 90 seconds. After the connection, we check whether it was successful and send the login and password:

If($conn_ftp) // connection was successful ( $login_result = @ftp_login($conn_ftp, "user", "pass"); // enter your login and password for FTP if($login_result) // login and password verification passed success(ftp_pasv($conn_ftp, TRUE);))

After checking the login and password, we need to decide on the passive mode and set it to TRUE or FALSE - this is necessary if further FTP functions will not work correctly. Now after defining the passive mode, we can create our folders, I will describe all the functions that may be useful to you in the future:

$file = ftp_mkdir($conn_ftp, "public_html/materials/345"); //Creating directory 345 in the materials folder, if the materials folder does not exist, //it will also be created, the same with the public_html folder (this directory //is indicated so that you can see the entire path, otherwise it’s just a folder with site) ftp_chdir($conn_ftp, "public_html/materials"); //If you definitely have a materials folder, then you don't have to write the entire //path, you can just go to it first and then create a folder 345 in it using //the following code ftp_mkdir ($conn_ftp, "345") ftp_chmod($ conn_ftp, 0777, $file); //All folders are created with mode 0755 by default, this command will allow you to change //it to 0777, which will allow you to add files to the created folder.

Now I’ll give a complete example of working code so you can see what it all looks like, for example, mine:

$dir_name = time(); //Here I create the folder name based on the time the script was launched $conn_ftp = @ftp_connect("your_ftp_server", 21, 5); if($conn_ftp) // connection was successful ( $login_result = @ftp_login($conn_ftp, "user", "pass"); // enter your login and password for FTP if($login_result) // login and password verification passed success ( ftp_pasv ($conn_ftp, TRUE); ftp_chdir ($conn_ftp, "public_html/materials"); ftp_mkdir ($conn_ftp, $dir_name); ftp_chmod($conn_ftp, 0777, $dir_name); ) )

It’s also worth saying a little about specifying directories when creating; if you specify a slash at the beginning, the folder will be created relative to the ftp root. When connecting to an FTP server you are always connecting to the root, so keep this in mind.