|
|
mkdir (PHP 3, PHP 4, PHP 5) mkdir -- Создаёт директорию Описаниеbool mkdir ( string pathname [, int mode [, bool recursive [, resource context]]] )
Пытается создать директорию, заданную в pathname.
Обратите внимание, что аргумент mode необходимо задавать
в виде восьмиричного числа (первой цифрой должен быть ноль).
На аргумент mode также влияет текущее значение umask, которое
можно изменить при помощи umask().
Замечание:
Аргумент mode игнорируется в Windows и стал необязательным начиная с
версии PHP 4.2.0.
По умолчанию mode равен 0777, что является самыми широкими правами
доступа. Для получения информации о режимах, обратитесь к странице
chmod().
Пример 1. Пример использования функции mkdir() |
<?php
mkdir("/path/to/my/dir", 0700);
?>
|
|
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Замечание:
Начиная с версии PHP 5.0.0 mkdir() также может
использоваться с некоторыми URL-обвёртками.
Обратитесь к Прил. M для получения списка обвёрток,
которые поддерживает mkdir().
Замечание:
Аргументы recursive и context
доступны начиная с версии PHP 5.0.0.
Замечание: Когда опция safe mode включена, PHP проверяет,
имеет ли каталог, с которым вы собираетесь работать, такой же UID (владельца),
как и выполняемый скрипт.
См. также описание функции rmdir().
dev at grind dot lv
09-Oct-2007 11:38
Another simple recursive mkdir function:
function Rmkdir($path){
$exp=explode("/",$path);
$way='';
foreach($exp as $n){
$way.=$n.'/';
if(!file_exists($way))
mkdir($way);
}
}
php_REMOVETHIS_ at htmledit dot com
03-Oct-2007 09:50
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...
Zingus J. Rinkle
10-Sep-2007 11: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
09-Sep-2007 01:36
dude at patabugen, try <?php umask(0); ?> before <?php mkdir($gallery."/".$name, 0755); ?>.
dude % patabugen ^ co " uk
05-Sep-2007 06: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 07: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 01: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.
21-Jul-2007 04: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
20-Jul-2007 09: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 06: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
15-May-2007 10: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
04-May-2007 08:17
When creating directories in Windows, trailing periods (".") are ignored. for example:
<?php
mkdir('c:/Buck Jr.',0755); mkdir('c:/Elipses...',0755); mkdir('c:/php.com',0755); ?>
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
12-Mar-2007 10: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
08-Mar-2007 08: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)
08-Jan-2007 03: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
20-Dec-2006 06: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
12-Nov-2006 07: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
09-Nov-2006 06: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)
06-Nov-2006 03: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
06-Nov-2006 09: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
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
27-Oct-2006 11: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 07: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 07: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
|