Php creating directory file
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
mkdir
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.
По умолчанию принимает значение 0777, что означает самые широкие права. Больше информации о правах доступа можно узнать на странице руководства функции chmod() .
Замечание:
Аргумент permissions игнорируется в Windows.
Обратите внимание, что аргумент permissions необходимо задавать в виде восьмеричного числа (первой цифрой должен быть ноль). На аргумент permissions также влияет текущее значение umask, которое можно изменить при помощи umask() .
Если указано значение true , то все родительские каталоги для указанного параметра directory также будут созданы, с теми же разрешениями.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Замечание:
Если создаваемый каталог уже существует, это считается ошибкой и будет возвращено значение false . Используйте функцию is_dir() или file_exists() , чтобы проверить, существует ли уже каталог, прежде чем пытаться его создать.
Ошибки
Выдаёт ошибку уровня E_WARNING , если директория уже существует.
Выдаёт ошибку уровня E_WARNING , если соответствующие права доступа блокируют создание директории.
Примеры
Пример #1 Пример использования функции mkdir()
Пример #2 Использование mkdir() с параметром recursive
// Желаемая структура папок
$structure = ‘./depth1/depth2/depth3/’ ;
?php
// Для создания вложенной структуры необходимо указать параметр
// $recursive в mkdir().
if (! mkdir ( $structure , 0777 , true )) die( ‘Не удалось создать директории. ‘ );
>
Смотрите также
- is_dir() — Определяет, является ли имя файла директорией
- rmdir() — Удаляет директорию
- umask() — Изменяет текущую umask
User Contributed Notes 5 notes
When using the recursive parameter bear in mind that if you’re using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie:
mkdir ( ‘/test1/test2’ , 0777 , true );
chmod ( ‘/test1/test2’ , 0777 );
?>
May result in «/test1/test2» having a mode of 0777 but «/test1» still having a mode of 0755 from the mkdir() call. You’d need to do:
mkdir ( ‘/test1/test2’ , 0777 , true );
chmod ( ‘/test1’ , 0777 );
chmod ( ‘/test1/test2’ , 0777 );
?>
This is an annotation from Stig Bakken:
The mode on your directory is affected by your current umask. It will end
up having ( and (not )). If you want to create one
that is publicly readable, do something like this:
$oldumask = umask ( 0 );
mkdir ( ‘mydir’ , 0777 ); // or even 01777 so you get the sticky bit set
umask ( $oldumask );
?>
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!
Remember to use clearstatcache()
. when working with filesystem functions.
Otherwise, as an example, you can get an error creating a folder (using mkdir) just after deleting it (using rmdir).
When creating a file using mkdir() the default root will be the DocumentRoot (in XAMPP) itself.
If you use mkdir(«myfile») in something.php, instead of creating the folder in includes, php will create it in the project folder
mkdir
По умолчанию принимает значение 0777, что означает самые широкие права. Больше информации о режимах доступа можно узнать на странице руководства функции chmod() .
Замечание:
Аргумент mode игнорируется в Windows.
Обратите внимание, что аргумент mode необходимо задавать в виде восьмеричного числа (первой цифрой должен быть ноль). На аргумент mode также влияет текущее значение umask, которое можно изменить при помощи umask() .
Разрешает создание вложенных директорий, указанных в pathname .
Замечание: Поддержка контекста была добавлена в PHP 5.0.0. Для описания контекстов смотрите раздел Потоки.
Возвращаемые значения
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Примеры
Пример #1 Пример использования функции mkdir()
Пример #2 Использование mkdir() с параметром recursive
// Желаемая структура папок
$structure = ‘./depth1/depth2/depth3/’ ;
?php
// Для создания вложенной структуры необходимо указать параметр
// $recursive в mkdir() .
if (! mkdir ( $structure , 0777 , true )) die( ‘Не удалось создать директории. ‘ );
>
Ошибки
Бросает ошибку уровня E_WARNING , если директория уже существует.
Бросает ошибку уровня E_WARNING , если соответствующие права доступа блокируют создание директории.
Примечания
Замечание: Когда опция safe mode включена, PHP проверяет, имеет ли каталог, с которым вы собираетесь работать, такой же UID (владельца), как и выполняемый скрипт.
Смотрите также
How to Create a New Directory Using PHP
In this article, we will show how to create a new directory on your website using PHP.
This means you don’t have to manually go to a FTP and create the directory. You can use the PHP language to create the new directory for you.
PHP is a powerful server-side scripting language. It can do many powerful things, one of them being creating directories on a website, backend work.
Creating directories using PHP can be very important. For example, say if you have a website that has users. Say, users store photos and documents on the website. Many times you probably want all of the user’s documents, including photos, in the user’s own directory. So, for example, when a user initially signs up for your website, you may just PHP dynamically to create a directory for that user. Then when the user decides to upload photos, documents, etc., you can store all in that directory that was created. More than likely, that directory name will be the same as the username, being that the username always has to be unique.
So this could be one of the ways how PHP can be used and why would it would be used to create directories.
So how do we do this? How do we create a directory?
And we create a directory through the PHP mkdir() function.
This function is very simple. All you need to know is that it takes one parameter, which is the name of the directory that you want to create.
So below we show the code.
Code
The code to create a directory called Pocahontas is shown below.
So the following code above creates a directory called Pocahontas.
You can also specify relative directories. So if I upload PHP file above to the root directory, it creates the directory, Pocahontas, in the root directory. So this website is http://www.learningaboutelectronics.com/. So this directory will be created at http://www.learningaboutelectronics.com/Pocahontas
Now you can also specify relative pathways. So if I wanted to create a directory Pocahontas in the Articles directory, I would specify the pathway. This is shown in the code below.
Now if you upload this PHP file to the root directory, it creates the directory, Pocahontas, in the Articles directory.
So the mkdir() function takes either the filename (if creating the directory in the directory this PHP file is uploaded to) or the pathway and the filename (if creating the directory in another directory other than the current directory).
The mkdir() function is pretty safe to use. What I mean by this is that, it will not create a new directory to a directory that already exists. So this function doesn’t run the risk of overwriting an existing directory that you may have that contains important files. If you attempt to use the mkdir() function to create a directory that already exists, PHP will throw a warning error, stating the following, Warning: mkdir() [function.mkdir]: File exists. So there’s one way of overwriting an important directory if a mistake or made or anything.
However, if you want to create a PHP code that shows if a directory has been successfully created or if it hasn’t been, you can use the following code shown below.
So this PHP code will output to you whether the directory has been successfully created or not, based on the fact if it’s already taken.
So PHP is very dynamic. It can create new directories on the fly. You don’t have to do it manually. It can be important for a wide variety of reasons, when doing it manually is painful and unnecessary, like the example I gave. If you have a website that has users and they can upload files, you probably want to create a directory for each user at the time they become users or at least at the time they upload files. Then you can just store all their files in that one folder.
So the mkdir() function is a great function, and this is how you can use it to create a new directory using PHP.