In response to kidlunch, you should note, if you read the manual carefully, that the recursive option has been implemented in PHP 5.0.0. So it *could* be (and certainly has been) useful for those using older versions of PHP...
mkdir
(PHP 4, PHP 5)
mkdir — ディレクトリを作る
説明
bool mkdir ( string $pathname [, int $mode [, bool $recursive [, resource $context]]] )指定したディレクトリを作成します。
パラメータ
- pathname
ディレクトリのパス。
- mode
モードは 0777 がデフォルトです。 これは最も緩やかなアクセス制限を意味します。 モードに関する詳細は chmod() をご覧ください。
注意: Windows では mode は無視されます。
モードを八進数で指定したくなることもあるかもしれません。 その場合は先頭にゼロをつける必要があります。 また、モードは、現在設定されている umask の影響も受けます。 umask を変更するには umask() を使用します。
- recursive
- context
注意: コンテキストのサポートは、 PHP 5.0.0 で追加されました。contexts の説明に関しては、 ストリーム を参照してください。
返り値
成功した場合に TRUE を、失敗した場合に FALSE を返します。
変更履歴
| バージョン | 説明 |
|---|---|
| 5.0.0 | recursive パラメータが追加されました。 |
| 5.0.0 | PHP 5.0.0 以降、mkdir() は いくつかの URL ラッパーを併用することが可能です。 mkdir() をサポートしているラッパーの一覧については、 付録 O. サポートされるプロトコル/ラッパー を参照ください。 |
| 4.2.0 | mode パラメータがオプションとなりました。 |
例
注意
注意: セーフモード が有効の場合、PHP は、 操作を行うディレクトリが、実行するスクリプトと同じ UID (所有者)を有しているか どうかを確認します。
参考
| rmdir() |
mkdir
php_REMOVETHIS_ at htmledit dot com
04-Oct-2007 01:50
04-Oct-2007 01:50
kidlunch at gmail dot com
25-Sep-2007 01:47
25-Sep-2007 01:47
Perhaps the commenting system is no longer being moderated, but why in the name of PHP Gods are people posting "recursion" functions?!?! Use the TRUE flag like
mkdir("/path/to/my/dir", 0700, TRUE);
.. so that the folders "path" and "to" and "my" get created on the fly if they don't exist already. PLEASE READ THIS MANUAL BEFORE POSTING!! If the proposed directory ends with a trailing slash and confuses Windows, then check the VARIABLE and change it, don't make convoluted functions that replicate a BUILT IN PHP FUNCTION!!!
Zingus J. Rinkle
11-Sep-2007 03:28
11-Sep-2007 03:28
Most mkpath() function I saw listed here seem long and convoluted.
Here's mine:
<?php
function mkpath($path)
{
if(@mkdir($path) or file_exists($path)) return true;
return (mkpath(dirname($path)) and mkdir($path));
}
?>
Untested on windows, but dirname() manual says it should work.
Michal Nazarewicz, mina86 at tlen dot pl
10-Sep-2007 05:36
10-Sep-2007 05:36
dude at patabugen, try <?php umask(0); ?> before <?php mkdir($gallery."/".$name, 0755); ?>.
dude % patabugen ^ co " uk
05-Sep-2007 10:30
05-Sep-2007 10:30
I had some problems creating directories and then not being able to access them because of permissions. The only way i have found to get around the problem was to create them with 0777 then chmod them to 4755.
<?PHP
mkdir($gallery."/".$name, 0755);
chmod($gallery."/".$name, 4755);
?>
Michal Nazarewicz, mina86 at mina86 dot com
27-Aug-2007 11:34
27-Aug-2007 11:34
On the other hand, splitting path on something else then a DIRECTORY_SEPARATOR may give unexpected results when someone accualy wants a file name with backslash in it! Moreover, neither Alan's nor pluto's code check for errors or return any value. Also, I don't like the isset($folder[$i]) technique -- there is a count() function you know.
<?php
function recursive_mkdir($path, $mode = 0777) {
$dirs = explode(DIRECTORY_SEPARATOR , $path);
$count = count($dirs);
$path = '.';
for ($i = 0; $i < $count; ++$i) {
$path .= DIRECTORY_SEPARATOR . $dirs[$i];
if (!is_dir($path) && !mkdir($path, $mode)) {
return false;
}
}
return true;
}
?>
It will only fail if someone specifies a mode which does not allow owner to create new entries in directory.
Borislav at rishworthchase dot net
23-Jul-2007 05:08
23-Jul-2007 05:08
I found that code provided by Alan H. is not very useful when you mixed \ and / path separator (commonly done in Windows environment). So find here revised version of the code:
<code>
<?php
function recursive_mkdir( $folder )
{
$folder = preg_split( "/[\\\\\/]/" , $folder );
$mkfolder = '';
for( $i=0 ; isset( $folder[$i] ) ; $i++ )
{
if(!strlen(trim($folder[$i])))continue;
$mkfolder .= $folder[$i];
if( !is_dir( $mkfolder ) ){
mkdir( "$mkfolder" , 0777);
}
$mkfolder .= DIRECTORY_SEPARATOR;
}
}
recursive_mkdir('c:/new_orders\\1/2\\3\\');
?>
</code>
Alan H.
22-Jul-2007 08:24
22-Jul-2007 08:24
Recursive mkdir! (Actually not recursive, but iterative... same effect.)
Useful to make *any* directory, such as ./foo/bar/baz, when ./foo or ./foo/bar doesn't exist.
This works for me and should work on all platforms. (Thanks, g4wk3.)
<?php
function recursive_mkdir( $folder )
{
$folder = explode( DIRECTORY_SEPARATOR , $folder );
$mkfolder = '';
for( $i=0 ; isset( $folder[$i] ) ; $i++ )
{
$mkfolder .= $folder[$i];
if( !is_dir( $mkfolder ) )
mkdir( "$mkfolder" , 0777);
$mkfolder .= DIRECTORY_SEPARATOR;
}
}
?>
pluton dot home at free dot fr
21-Jul-2007 01:56
21-Jul-2007 01:56
for php-unix users that needs to create a recursive path
for php releases < 5.0.0
here is a 1-line function using system mkdir call
function mk_recurse_dir($dir,$mode = 0775) {
passthru("mkdir -m ".$mode." -p ".$dir);
}
g4wx3
18-Jul-2007 10:56
18-Jul-2007 10:56
This is a little function I use instead of mkdir.
It makes the full folder path, even if it occur that folders are missing.
Easy to understand&very handy even if you are sure no folders are missing
<?php
function createfolder( $folder )
{
$folder = explode( "/" , $folder );
$mkfolder = '';
for( $i=0 ; isset( $folder[$i] ) ; $i++ )
{
$mkfolder .= $folder[$i] . '/';
if( !is_dir( $mkfolder ) )
mkdir( "$mkfolder" , 0777);
}
}
?>
*I read that php 5.2.6 contain a bug on wamp, and there will no folder be created if the path ends on '/'
So i will modify a little this function in order that the folder path doesn't end on '/'.
UNTESTED
<?php
function createfolder( $folder )
{
$folder = explode( "/" , $folder );
$mkfolder = '';
for( $i=0 ; isset( $folder[$i] ) ; $i++ )
{
$mkfolder .= $folder[$i];
if( !is_dir( $mkfolder ) )
mkdir( "$mkfolder" , 0777);
$mkfolder .= '/';
}
}
?>
alex_web at mail dot ru
16-May-2007 02:07
16-May-2007 02:07
One note about recursive dir creating. I consider it`s better to use original function instead of cycles or recursion. Smth like this:
<?php
mkdir(str_replace('/',DIRECTORY_SEPARATOR,$dirname),null,true);
?>
kendsnyder at gmail dot com
05-May-2007 12:17
05-May-2007 12:17
When creating directories in Windows, trailing periods (".") are ignored. for example:
<?php
mkdir('c:/Buck Jr.',0755); // on Windows creates "c:/Buck Jr"
mkdir('c:/Elipses...',0755); // on Windows creates "c:/Elipses"
mkdir('c:/php.com',0755); // on Windows creates "c:/php.com"
?>
This is a Window's quirk, not a php shortcoming--meaning that you get the same results from a Window's command prompt.
glenn at bengeweb dot co dot nz
13-Mar-2007 02:00
13-Mar-2007 02:00
I've discovered that since my (shared) hosting provider upgraded to PHP 5.1.6 , a script containing this mkdir doesn't work:
<?php
mkdir('/home/benge/photos/gallery1/extra_large/', 0777);
?>
but this does work:
<?php
mkdir('/home/benge/photos/gallery1/extra_large', 0777);
?>
the difference being, the trailing slash "/" after "extra_large.
There were three ways to fix the problem:
1. remove the trailing slash from the script code
2. downgrade to < PHP 5.1.6
3. turn safe mode off
I went with option 1.
sean at pedlr dot com
09-Mar-2007 01:58
09-Mar-2007 01:58
It should be noted that although the documentation says that the default permissions for mkdir are 0777, this is not always the case.
I'm running LAMP and without explicitly setting the permissions, the directories created had permissions of 0755.
Ari Schulman (ario [] mail utexas edu)
09-Jan-2007 08:02
09-Jan-2007 08:02
Re: john 4t idserver d0t org, and djneoform at gmail dot com's posts from 27 Oct 2006:
On Windows systems, several keywords are reserved and cannot be used as filenames, in addition to just CON and PRN. Attempting to create a folder with one of these names using mkdir will throw the unhelpful error "Invalid argument". According to http://msdn.microsoft.com/library/default.asp ?url=/library/en-us/fileio/fs/naming_a_file.asp :
"Do not use the following reserved device names for the name of a file: CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names followed by an extension, for example, NUL.tx7.
Windows NT: CLOCK$ is also a reserved device name."
These keywords are also case-insensitive. I don't know what problems are posed by using these keywords with extensions, but I successfully created a folder named "con_f".
fantasysportswire at yahoo dot com
21-Dec-2006 11:07
21-Dec-2006 11:07
One small correction on a note from Frank in June 2006 on recursive directories under Windows.
First - this should be in the documentation as its the only function that I know of that php does not fix the slashes automatically.
Franks note stated:
<?php
$mypath="testdir\subdir\test";
mkdir($mypath,0777,TRUE);
?>
This doesn't work in windows:
<?php
$mypath="testdir/subdir/test";
mkdir($mypath,0777,TRUE);
?>
----
This will work a bit better :)
<?php
$mypath="testdir\\subdir\\test";
mkdir($mypath,0777,TRUE);
?>
v1d4l0k4 {at} gmail.com
13-Nov-2006 12:42
13-Nov-2006 12:42
The 'mkdir' function doesn't function correctly on Windows when the pathname contain space(s) on the final. PHP returns a warning, and the directory isn't created:
Warning: mkdir() [function.mkdir]: Invalid argument in X on line Y
Temporary fix: use trim() on the pathname
Besides, if the pathname contain space(s) on the start, the directory is created when couldn't even so (in accordance with the behavior of Windows Explorer).
~ v1d4l0k4
brendan at bloodbone dot ws
10-Nov-2006 11:10
10-Nov-2006 11:10
The only function that I could get to work for making recursive directories was kungla at gmail dot com's. That might save some people trouble. (PHP4)
V-Tec (vojtech.vitek at seznam dot cz)
07-Nov-2006 08:42
07-Nov-2006 08:42
This is the way how to create all the path, if you don't
know exactly what folders and sub-folders really exist.
The function works with absolute or relative
path of some folder or file.
It works correctly.
<?
function mk_dir($path, $rights = 0777)
{
$folder_path = array(
strstr($path, '.') ? dirname($path) : $path);
while(!@is_dir(dirname(end($folder_path)))
&& dirname(end($folder_path)) != '/'
&& dirname(end($folder_path)) != '.'
&& dirname(end($folder_path)) != '')
array_push($folder_path, dirname(end($folder_path)));
while($parent_folder_path = array_pop($folder_path))
if(!@mkdir($parent_folder_path, $rights))
user_error("Can't create folder \"$parent_folder_path\".");
}
mk_dir('example_1/relative/path/of/new-folder/file.ext');
mk_dir('example_2/relative/path/of/new-folder');
mk_dir('/example_3/absolute/path/of/new-folder/file.ext');
mk_dir('/example_4/absolute/path/of/new-folder');
?>
puckje_piet at hotmail dot com
07-Nov-2006 02:07
07-Nov-2006 02:07
Note that, well at least in cpanel10, you will be unable to remove the folder from the folder list if you've created it with mkdir(). You will need an FTP program to remove the folder. If you that doesn't work, you can write a small script
<?php
/*Remove directories if all other fails*/
rmdir($_GET['rem'])
?>
save as a file. You can acces it by FILENAME.php?rem=PATH_TO_FILE. I suggest you protect this with a password though
-Duveaux
john 4t idserver d0t org
28-Oct-2006 03:27
28-Oct-2006 03:27
Windows reserves the names PRN and CON as they are devices in DOS. Back in the day, you could easily print a document via "type filename.txt > PRN".
CON is the console. To create a file from scratch under dos you do: COPY CON filename.txt
It then allows you to type until you press CTRL-D.
djneoform at gmail dot com
27-Oct-2006 11:28
27-Oct-2006 11:28
Forewarning to windows users.
If you try to create a directory called "prn" or "con" windows will reject the name and cause an error.
apparently (i found this out the hard way) windows simply cannot have directories by those names, who knows why..
mroy at matthewroy dot com
11-Oct-2006 11:51
11-Oct-2006 11:51
fixed bug with the previous script:
else if (!ftp_site($connection, "CHMOD 0777 $newDir"){ // change attributes
is missing an ")" so it should read:
else if (!ftp_site($connection, "CHMOD 0777 $newDir")) { // change attributes
Lars Pätzold
29-Aug-2006 09:44
29-Aug-2006 09:44
Just a small addition to Han Van den Hoof's ftp script which is really useful for scripts on shared servers.
I added a chmod command. This is necessary if you want to access the directory later via script.
I also fixed the small bug with the 2 variables connection & conn_id ;)
And last not least ftp connection is closed even if ftp commands fail.
Sometimes ftp login will fail due to bad luck. Therefore one should add a loop for retrying.
<?php
// create directory through FTP connection
function FtpMkdir($path, $newDir) {
$server='ftp.yourserver.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp server
$user = "me";
$pass = "password";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
if (!ftp_chdir($connection, $path)) { // go to destination dir
$r = false;
} else if (!ftp_mkdir($connection,$newDir)) { // create directory
$r = false;
} else if (!ftp_site($connection, "CHMOD 0777 $newDir") { // change attributes
$r = false;
} else {
$r = $newDir;
}
}
ftp_close($connection); // close connection
return $r;
}
?>
PHGN
14-Aug-2006 03:13
14-Aug-2006 03:13
I've been wrestling with mkdir on a server with safe mode turned on (I think, I kept getting barmy permissions on the new dirs).
In the end the solution was to use:
exec (mkdir ...
exec (chmod ...
For this to work I had to use the setuid bit on the script itself. I tried this with the mkdir() function, but to no avail. (To do the setuid bit I ran chmod 4775 on the script file from the command line.)
malmsteenforce at tlen dot pl
20-Jul-2006 07:39
20-Jul-2006 07:39
I have trouble with recursively of mk_dir function ,with slashes and backslashes, so I`ve solved this below :
<?
function mkpath($path)
{
$dirs=array();
$path=preg_replace('/(\/){2,}|(\\\){1,}/','/',$path); //only forward-slash
$dirs=explode("/",$path);
$path="";
foreach ($dirs as $element)
{
$path.=$element."/";
if(!is_dir($path))
{
if(!mkdir($path)){ echo "something was wrong at : ".$path; return 0; }
}
}
echo("<B>".$path."</B> successfully created");
}
mkpath("./dir1\dir2/dir3\\\dir4////dir5"); //this works without errors
?>
kungla at gmail dot com
18-Jul-2006 09:41
18-Jul-2006 09:41
Somehow the recursive version of mkdir didn't work for me on Mac and the workaraounds listed below alsow didn't work for me, so heres my solution:
<?php
function mkdir_r($dirName, $rights=0777){
$dirs = explode('/', $dirName);
$dir='';
foreach ($dirs as $part) {
$dir.=$part.'/';
if (!is_dir($dir) && strlen($dir)>0)
mkdir($dir, $rights);
}
}
?>
Tested and works ;)
Frank
13-Jul-2006 06:51
13-Jul-2006 06:51
cost me an hour to get recursive switch to work in windows with php 5.2.0, so share it here. The key is backward slash in windows , this php version doesn't recognize forward slash as valid path separator for mkdir(), though other functions support forward-slashed paths just fine. The following example works in Windows:
<?php
$mypath="testdir\subdir\test";
mkdir($mypath,0777,TRUE);
?>
This doesn't work in windows:
<?php
$mypath="testdir/subdir/test";
mkdir($mypath,0777,TRUE);
?>
jamespilcher1hotmail
08-Apr-2006 09:53
08-Apr-2006 09:53
one small gotcha:
mkdir(""), mkdir(false), and mkdir(null) give a "file exists" error. this is also true of a directory name consisting of any string that only contains space characters.
(this was on php 5.1.2 on Windows 2000)
bat at flurf dot net
22-Mar-2006 02:23
22-Mar-2006 02:23
A little understanding of LISPlike programming makes this sort of task (recursive mkdir()ing in PHP4) much simpler. This version works nicely:
<?php
function MakeDirectory($dir, $mode = 0755)
{
if (is_dir($dir) || @mkdir($dir,$mode)) return TRUE;
if (!MakeDirectory(dirname($dir),$mode)) return FALSE;
return @mkdir($dir,$mode);
}
?>
How it works: line one attempts to make the directory, and returns TRUE if it works or if it already exists. That's the easy case if the parent directories all exist.
Line two trims off the last directory name using dirname(), and calls MakeDirectory recursively on that shorter directory. If that fails, it returns FALSE, but otherwise we come out of it knowing that the parent directory definitely exists.
Finally, presuming the recursive call worked, once we get to line three we can create the requested directory.
Note the use of @ to suppress warning messages from mkdir.
The beauty of this is that if, say, the great-grandparent directory exists but the grandparent and parent directories don't, the function will simply call itself recursively until it gets high enough up the tree to do some work, then carry on unwinding back until all the new directories have been created.
This is pretty bog-standard recursive programming. Anyone who can't wrap their head around it after a few minutes of concentration should probably try a career in sales.
Ali Baba
11-Mar-2006 06:26
11-Mar-2006 06:26
Greg, your code does not work for me; maybe it has a bug or we have configuration changes. Anyway, this one works to create recursively the directory DIRECTORY.
<?
define ("DIRECTORY", "/tmp/mydir/mysubdir");
do {
$dir = DIRECTORY;
while (!is_dir($dir)) {
$basedir = dirname($dir);
if ($basedir == '/' || is_dir($basedir))
mkdir($dir,0777);
else
$dir=$basedir;
}
} while ($dir != DIRECTORY);
?>
19-Jan-2006 02:48
function mkdirs($dir, $mode = 0777, $recursive = true) {
if( is_null($dir) || $dir === "" ){
return FALSE;
}
if( is_dir($dir) || $dir === "/" ){
return TRUE;
}
if( mkdirs(dirname($dir), $mode, $recursive) ){
return mkdir($dir, $mode);
}
return FALSE;
}
baldurien at club-internet dot fr
18-Jan-2006 08:14
18-Jan-2006 08:14
For those wandering about the $recursive flag of mkdir in php5, this function will do what you want (� la java) in php 4:
<?php
/**
* Create a new directory, and the whole path.
*
* If the parent directory does not exists, we will create it,
* etc.
*
* @param string the directory to create
* @param int the mode to apply on the directory
* @return bool return true on success, false else
*/
function mkdirs($dir, $mode = FS_RIGHTS_D) {
$stack = array(basename($dir));
$path = null;
while ( ($d = dirname($dir) ) ) {
if ( !is_dir($d) ) {
$stack[] = basename($d);
$dir = $d;
} else {
$path = $d;
break;
}
}
if ( ( $path = realpath($path) ) === false )
return false;
$created = array();
for ( $n = count($stack) - 1; $n >= 0; $n-- ) {
$s = $path . '/'. $stack[$n];
if ( !mkdir($s, $mode) ) {
for ( $m = count($created) - 1; $m >= 0; $m-- )
rmdir($created[$m]);
return false;
}
$created[] = $s;
$path = $s;
}
return true;
}
?>
The main idea here is to use a stack to store the invalid dirname (using basename/dirname), and then pop each item on the stack to create directory from a valid path (here: $path = realpath($path). If we fails creating one directory, we must remove them in the reverse order of creation (stackes :)).
This works on Windows XP, and it should work on Linux (actually, I did not tested it).
Note that this code is a part of one of my classes (named FileSystem), and that you should use your own basename/realpath/dirname/mkdir/rmdir function instead of php one (even if you use them behind). This will allow you to separate the item of a FileSystem from what is it really (FTP? Local ? Telnet? Teletubbies?)
Sean at seanj dot jcink dot com
24-Dec-2005 11:10
24-Dec-2005 11:10
Mkdir will work on parent directories as long as file permissions are right and the openbase restriction is not on.
~Sean
trond at trondhuso dot no
14-Dec-2005 05:10
14-Dec-2005 05:10
While researching for this function, I have found out that - at least on my system - mkdir only works when the parent directory is the one your script is in.
eg:
you want to create a directory tmp
mkdir ('tmp', 0775);
will create /path/to/your/script/tmp
but if you this
mkdir ('/path/to/your/tmp', 0755);
or
mkdir ('../tmp', 0755);
both will cause an error - permission denied.
Trond
Slawek Petrykowski
16-Nov-2005 04:20
16-Nov-2005 04:20
Kevin Cook wrote: "I could not get the sticky bit set properly using the octal mode: 2775 (rwxrwsr-x)"
Try 02775 instead, Kevin.
killroy /at/ gmail
03-Nov-2005 02:49
03-Nov-2005 02:49
Here's a 3 line version, only superficially tested on win:
<?php
function mkdir_recursive($dirName){
foreach(split('/',dirname($dirName)) as $dirPart)mkdir($newDir="$newDir$dirPart/");
}
?>
Kevin Cook
03-Nov-2005 02:14
03-Nov-2005 02:14
I could not get the sticky bit set properly using the octal mode: 2775 (rwxrwsr-x)
$foo='my_directory';
$old_umask = umask(0);
mkdir($foo,2775);
umask($old_umask);
using the above lines renders a directory with permissions:
d-wx-wSrwt 2 www www 4096 Nov 2 11:43 my_directory
Not exactly what I was looking for.
This gets closer to the mark:
$foo='my_directory';
$old_umask = umask(0);
mkdir($foo,0777); // the default chmod
umask($old_umask);
drwxrwsrwx 2 www www 4096 Nov 2 11:46 my_directory
ephraim at coder-board dot info
11-Oct-2005 03:38
11-Oct-2005 03:38
When safe_mode is enabled, and you create a directory via mkdir, you can't create a second inside the first because the first folder's user is that one of the webserver and not that one of the script. This is dumb and very annoying :(
greg at NOserberusSPAM dot co dot uk
05-Oct-2005 05:51
05-Oct-2005 05:51
Recursive directory creation routine.
This could be adapted to work on Windows but this code is written for use on a Linux/Unix based machine.
<?php
$working_directory = '/path/to/my/work';
do {
$dir = $working_directory;
while (!@mkdir($dir,0777)) {
$dir = dirname($dir);
if ($dir == '/' || is_dir($dir))
break;
}
} while ($dir != $working_directory);
?>
funke
17-Sep-2005 04:51
17-Sep-2005 04:51
Ive onlybeen coding in PHP for a couple of months so i Don't have all the syntax tricks down yet.
I wrote this function to create all the dirs in a path if they don't exist. its not actually recursive but i was to lazy to change the name :)
theoretically i want it to work for both win and nix. As soon my project manager gets me a win box i'm gonna test it out. anyrevisions to the function below would be appreciated.
<?php
// \
function recur_mkdirs($path, $mode = 0777) //creates directory tree recursively
{
//$GLOBALS["dirseparator"]
$dirs = explode($GLOBALS["dirseparator"],$path);
$pos = strrpos($path, ".");
if ($pos === false) { // note: three equal signs
// not found, means path ends in a dir not file
$subamount=0;
}
else {
$subamount=1;
}
for ($c=0;$c < count($dirs) - $subamount; $c++) {
$thispath="";
for ($cc=0; $cc <= $c; $cc++) {
$thispath.=$dirs[$cc].$GLOBALS["dirseparator"];
}
if (!file_exists($thispath)) {
//print "$thispath<br>";
mkdir($thispath,$mode);
}
}
}
?>
Steven Ng
09-Jun-2005 03:37
09-Jun-2005 03:37
I had to remove the $path in the CHMOD command before the function worked for me. The function was at the $path directory prior to initiating the CHMOD command, so it tried to go down the $path directory again.
// create directory through FTP connection
function FtpMkdir($path, $newDir) {
$server='ftp.server.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp server
$user = "me";
$pass = "pass";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
ftp_chdir($connection, $path); // go to destination dir
if(ftp_mkdir($connection, $newDir)) { // create directory
ftp_site($connection, "CHMOD 777 $newDir") or die("FTP SITE CMD failed.");
return $newDir;
} else {
return false;
}
ftp_close($connection); // close connection
}
}
FtpMkdir("path","dir");
David Pullen
29-May-2005 09:20
29-May-2005 09:20
A simple recursive mkdir function:
<?php
function RecursiveMkdir($path)
{
// This function creates the specified directory using mkdir(). Note
// that the recursive feature on mkdir() is broken with PHP 5.0.4 for
// Windows, so I have to do the recursion myself.
if (!file_exists($path))
{
// The directory doesn't exist. Recurse, passing in the parent
// directory so that it gets created.
RecursiveMkdir(dirname($path));
mkdir($path, 0777);
}
}
if (!file_exists("/path/to/my/file"))
{
// Call the recursive mkdir function since the "recursive" feature
// built in to mkdir() is broken.
RecursiveMkdir("/path/to/my/file");
}
?>
roth at egotec dot com
23-May-2005 03:43
23-May-2005 03:43
The 'mkdir' function doesn't function correctly on Windows when the path
contains forward slashes. The part of the path with the forward slashes
doesn't get created.
mkdir('c:/a/b/c/d', 0775, true);
You get the error message:
Warning: mkdir() [function.mkdir]: No such file or directory
Please use backslashes under Windows or use the constant DIRECTORY_SEPARATOR.
mkdir('c:\a\b\c\d', 0775, true);
mkdir('c:'.DIRECTORY_SEPARATOR.'a'.
DIRECTORY_SEPARATOR.'b'.
DIRECTORY_SEPARATOR.'c'.
DIRECTORY_SEPARATOR.'d', 0775, true);
webmaster2007 at home dot nl
29-Apr-2005 12:27
29-Apr-2005 12:27
Maybe you can use this:
<?php
function open_dir($dir, $newdir){ //The function that will copy the files
if(file_exists($dir) && file_exists($newdir)){
$open_dir=opendir($dir);
while (false !== ($file = readdir($open_dir))) {
if($file != "." && $file != ".."){
if(file_exists($newdir."/".$file) && filetype($newdir."/".$file."/") != "dir"){
unlink($newdir."/".$file);
}
if(filetype($dir."/".$file."/") == "dir"){
if(!file_exists($newdir."/".$file."/")){
mkdir($newdir."/".$file."/");
open_dir($dir."/".$file."/", $newdir."/".$file."/");
}
}
else {
copy($dir."/".$file."/", $newdir."/".$file);
}
}
}
}
}
open_dir("Your source map", "Your destination map"); //Here you can fill in your source en destination map
?>
yknot7 at hotmail dot com
14-Apr-2005 03:59
14-Apr-2005 03:59
Add permission using CHMOD in the above mentioned
// create directory through FTP connection
function FtpMkdir($path, $newDir) {
$server='ftp.server.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp server
$user = "me";
$pass = "pass";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
ftp_chdir($connection, $path); // go to destination dir
if(ftp_mkdir($connection, $newDir)) { // create directory
ftp_site($connection, "CHMOD 777 $path/$newDir") or die("FTP SITE CMD failed.");
return $newDir;
} else {
return false;
}
ftp_close($connection); // close connection
}
}
FtpMkdir("path","dir");
mdap at dap dot ro
05-Apr-2005 06:26
05-Apr-2005 06:26
at this example (from mkdir) :
<?php
// create directory through FTP connection
function FtpMkdir($path, $newDir) {
$server='ftp.yourserver.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp server
$user = "me";
$pass = "password";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
ftp_chdir($connection, $path); // go to destination dir
if(ftp_mkdir($connection,$newDir)) { // create directory
return $newDir;
} else {
return false;
}
ftp_close($conn_id); // close connection
}
}
?>
i found a mistake at the last line before } :
ftp_close($conn_id); // close connection
is not $conn_id is $connection
Protik Mukherjee
04-Mar-2005 02:29
04-Mar-2005 02:29
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!
Aleks Peshkov
26-Feb-2005 10:18
26-Feb-2005 10:18
function makeDirs($strPath, $mode = 0777) //creates directory tree recursively
{
return is_dir($strPath) or ( makeDirs(dirname($strPath), $mode) and mkdir($strPath, $mode) );
}
The simpler is the better.
par dot sandgren at gmail dot com
11-Feb-2005 05:29
11-Feb-2005 05:29
You might want to upload files into random named dir's, just to make it harder to guess the link. But still have some ID to know whats in there.
<?php
$dirLength = rand(30, 40);
$projectID = $_POST['pid']; // ID from database perhaps?
$rndName = "";
for($i=0; $i<$dirLength; $i++)
{
$rnd = rand(1, 3);
if($rnd == 1)
$rndName = $rndName . chr(rand(97, 122));
else if($rnd == 2)
$rndName = $rndName . chr(rand(65, 90));
else
$rndName = $rndName . chr(rand(48, 57));
}
$dirName = $projectID . "-" . $rndName;
mkdir($dirname);
?>
aidan at php dot net
03-Oct-2004 11:17
03-Oct-2004 11:17
This function creates a directory structure recursively.
http://aidanlister.com/repos/v/function.mkdirr.php
Han Van den Hoof
10-Nov-2003 03:28
10-Nov-2003 03:28
If you're on a shared *nix server, a directory created through mkdir() will not be assigned to you, but to the user that your host's server or php process is running under, usually 'nobody', 'apache' or 'httpd'.
In practice, this means that you can create directories, even add files to them, but you can't delete the directory or its contents nor change permissions.
It is therefore advised to create directories through PHP's FTP API. Here's a function I wrote:
<?php
// create directory through FTP connection
function FtpMkdir($path, $newDir) {
$server='ftp.yourserver.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp server
$user = "me";
$pass = "password";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
ftp_chdir($connection, $path); // go to destination dir
if(ftp_mkdir($connection,$newDir)) { // create directory
return $newDir;
} else {
return false;
}
ftp_close($conn_id); // close connection
}
}
?>
Hope this comes in handy for someone.
28-Jun-2003 08:00
You might notice that when you create a new directory using this code:
mkdir($dir, 0777);
The created folder actually has permissions of 0755, instead of the specified
0777. Why is this you ask? Because of umask(): http://www.php.net/umask
The default value of umask, at least on my setup, is 18. Which is 22 octal, or
0022. This means that when you use mkdir() to CHMOD the created folder to 0777,
PHP takes 0777 and substracts the current value of umask, in our case 0022, so
the result is 0755 - which is not what you wanted, probably.
The "fix" for this is simple, include this line:
$old_umask = umask(0);
Right before creating a folder with mkdir() to have the actual value you put be
used as the CHMOD. If you would like to return umask to its original value when
you're done, use this:
umask($old_umask);
aulbach at unter dot franken dot de
23-Jul-1999 06:37
23-Jul-1999 06:37
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);
?>