Create folder in php script

PHP-функция mkdir()

Функция PHP mkdir() применяется для создания каталога, заданного в pathname . Каталог создается со значением режима доступа по умолчанию 0777 .

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

Пример использования функции mkdir () :

Возвращаемое значение . Эта функция возвращает значение TRUE в случае удачного завершения или FALSE при возникновении ошибки.

Дополнительная информация . Эта функция выдает ошибку уровня E_WARNING , если директория уже существует. Предупреждение также выдается, если соответствующие разрешения предотвращают создание каталога и PHP mkdir не работает.

Версия PHP . Функция mkdir () доступна в PHP 4 , PHP 5 , PHP 7 .

Релевантные функции . is_dir() — указывает, является ли имя файла каталогом. rmdir() – удаляет каталог.

Параметры

pathname

Параметр pathname используется для указания пути к каталогу. Это обязательный параметр.

mode

Параметр mode задает режим доступа к директории. Значением по умолчанию является 0777 , что обеспечивает максимально возможный доступ. Этот параметр является необязательным.

Необходимо помнить, что параметр mode игнорируется в Windows .

recursive

Разрешает создание вложенных каталогов в указанном пути. Этот параметр является необязательным. Он был добавлен в PHP 5 .

context

Используется для указания контекста дескриптора файла. Контекст — это набор опций, которые могут изменять поведение потока. Он был добавлен в PHP 5 . Этот параметр PHP mkdir() также является необязательным.

Примеры

Примеры использования функции mkdir () :

Здесь параметр recursive используется для создания вложенных каталогов.

Советы

При использовании PHP mkdir recursive следует помнить, что, применяя chmod() после mkdir () , чтобы задать режим, не изменяя его значением uchar() , необходимо вызвать chmod() во всех созданных каталогах. Например:

Приведенный выше код может привести к результату « /test1/test2 » с режимом 0777 , но « /test1 » по-прежнему имеет режим 0755 от вызова mkdir() . Необходимо указать:

Источник

mkdir

Attempts to create the directory specified by directory .

Parameters

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

The permissions are 0777 by default, which means the widest possible access. For more information on permissions, read the details on the chmod() page.

Note:

permissions is ignored on Windows.

Note that you probably want to specify the permissions as an octal number, which means it should have a leading zero. The permissions is also modified by the current umask, which you can change using umask() .

If true , then any parent directories to the directory specified will also be created, with the same permissions.

Return Values

Returns true on success or false on failure.

Note:

If the directory to be created already exists, that is considered an error and false will still be returned. Use is_dir() or file_exists() to check if the directory already exists before trying to create it.

Errors/Exceptions

Emits an E_WARNING level error if the directory already exists.

Emits an E_WARNING level error if the relevant permissions prevent creating the directory.

Examples

Example #1 mkdir() example

Example #2 mkdir() using the recursive parameter

// Desired directory structure
$structure = ‘./depth1/depth2/depth3/’ ;

// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.

if (! mkdir ( $structure , 0777 , true )) die( ‘Failed to create directories. ‘ );
>

See Also

  • is_dir() — Tells whether the filename is a directory
  • rmdir() — Removes directory
  • umask() — Changes the current 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/’ ;

// Для создания вложенной структуры необходимо указать параметр
// $recursive в mkdir() .

if (! mkdir ( $structure , 0777 , true )) die( ‘Не удалось создать директории. ‘ );
>

Ошибки

Бросает ошибку уровня E_WARNING , если директория уже существует.

Бросает ошибку уровня E_WARNING , если соответствующие права доступа блокируют создание директории.

Примечания

Замечание: Когда опция safe mode включена, PHP проверяет, имеет ли каталог, с которым вы собираетесь работать, такой же UID (владельца), как и выполняемый скрипт.

Смотрите также

Источник

Create folder in php script

  • 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 ?

Источник

Читайте также:  Php artisan ui vue auth
Оцените статью