Php create file and folders

Create folder using PHP

Why do you think I cant create a folder inside «job_images» if permission is set to 755 but allows me to create a folder inside «job_images» if «job_images» permission is set to 777? 5 means Read & Execute, without write, so you can’t make new directory.

Create folder using PHP

Can we create folder with PHP code? I want that whenever a new user create his new account his folder automatically creates and a PHP file also created. Is this possible?

Purely basic folder creation

Basic file creation

Use the a or a+ switch to add/append to file.

EDIT:

This version will create a file and folder at the same time and show it on screen after.
 $file = fopen($dir . '/' . $file_to_write,"w"); // a different way to write content into // fwrite($file,"Hello World."); fwrite($file, $content_to_write); // closes the file fclose($file); // this will show the created file from the created folder on screen include $dir . '/' . $file_to_write; ?> 

You can create a directory with PHP using the mkdir() function.

You can use fopen() to create a file inside that directory with the use of the mode w .

w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

$structure = './depth1/depth2/depth3/'; if (!mkdir($structure, 0, true))

. You can then use copy() to duplicate a PHP file, although this sounds incredibly inefficient.

File — Create folder using PHP, Add a comment. 16. You can create a directory with PHP using the mkdir () function. mkdir («/path/to/my/dir», 0700); You can use fopen () to create a file …

Php: create directory on form submit?

I am wondering what I am doing wrong. I’m inside of PATH and I want to create a folder inside of PATH. I want to check if the folder already exists and, if not, create one. Getting the name of the folder from an input field with name of «dirname».

It might be a good idea to make sure that the directory you are handling is indeed a directory. This code works. edit as you please.

define("PATH", "/home/born05/htdocs/swish_s/Swish"); $test = "set"; $_POST["dirname"] = "test"; if (isset($test)) < //get value of inputfield $dir = $_POST['dirname']; //set the target path ?? $targetfilename = PATH . '/' . $dir; if (!is_file($dir) && !is_dir($dir)) < mkdir($dir); //create the directory chmod($targetfilename, 0777); //make it writable >else < echo "exists and is a valid dir"; > 

Good luck!

Edited: comment was a good hint 😉

Читайте также:  Python all list elements to string

it’s not a file, it’s a directory!

@codeworxx file_exists can be used to check a directory as well..

Php create directory, The php file that is running the code is in www/console and the directory that I am trying to create is in www/images/gallery. I have tried many variations of setting …

Create writable directories

For a project I’m implementing a file-upload system. For every user account I would like the script to create a different sub-folder. Lets say their user_id’s.

Each time a user is added, the system will create a new sub-folder for their own uploads. For example:

Uploads/ — user1 — user2 — user3

By executing mkdir(‘Uploads/’.$user_id, 0777); it will create a new subfolder. Everything is fine.

However my application is not able to write to this folder. How do I have php make directories with the required file permissions? I have tried using chmod with no success.

This might help chmod and mkdir

$dirMode = 0777; mkdir($directory, $dirMode, true); // chmod the directory since it doesn't seem to work on recursive paths chmod($directory, $dirMode); 

For mkdir, mode is ignored on Windows. and 0777 is by default. and the third param is recursive which allows the creation of nested directories specified in the pathname.

sometimes the directory created with another mode than specified ( 0755 instead 0777 etc). to solve that use :

Mkdir — php: create directory on form submit?, I’m inside of PATH and I want to create a folder inside of PATH. I want to check if the folder already exists and, if not, create one. Getting the name …

Cannot create a directory using mkdir

So I’m trying to develop a script where all users can upload an image to a dynamically created folder.

$newID = 1 mkdir('uploads/job_images/'.$newID.'/',0755); 

This will create a folder inside «uploads/job_images» which is already set up.

My problem is that if «job images» permission is set to 755 or 766 it wont let me create a directory. But when I try to set the «job_images» permission to 777 it allows me to create a directory. But they say 777 is a security risk. Why do you think I cant create a folder inside «job_images» if permission is set to 755 but allows me to create a folder inside «job_images» if «job_images» permission is set to 777?

The created folder also have the «owner/group» set to 99/99(nobody). Is that owner group okay?

  1. Can I do it without using 777 to «job_images» folder or leaving it to 777 is okay?
  2. Do I need to change the owner of the created folder? I might someday need to delete those folders.
  3. How do I default the group of those created folders by the users of the website?

Try to use sudo chown to change the ownership of your directory to Apache (or whatever software/service/daemon running your code :). If you are the creator of the directory, you don’t need to use sudo (but in most Unix/Linux system you’ll need to have the target group permissions too).

Читайте также:  Trigger javascript from button

Please read about Numeric Notation of filesystem permissions. The first 7 indicating that the owner group have right to Read, Write and Execute your file. 5 means Read & Execute, without write, so you can’t make new directory.

I`ve the same problem, PHP restrict some functions:

Functions restricted by safe mode The solution is set the directive safe_mode_gid=On in the /etc/php5/apache2/phi.ini configuration file.

See safe_mode_gid directive It works for my LAMP server Ubuntu 12.04

PHP create directory with 777 permission in Windows, if you are creating a directory with PHP its owned by the same user who owns the apache process. Now this user can create file on that folder. …

Источник

Работа с файлами в PHP

С помощью функции file_get_contents() можно получить содержимое файла:

Также мы можем получить html-код какой-либо страницы в интернете:

'; echo file_get_contents('https://ya.ru'); echo '';

Но работает это далеко не для всех сайтов, у многих есть защита от такого примитивного парсинга.

Чтение файла: file()

Функция file() позволяет получить содержимое файла в виде массива. Разделителем элементов является символ переноса строки.

Создадим в корне сайта файл data.txt со следующим содержимым:

Теперь запустим скрипт index.php со следующим кодом:

При запуске этого скрипта мы получим в браузере:

array(3) < [0]=>string(7) "Vasya " [1]=> string(7) "Petya " [2]=> string(5) "Gosha" >

Заметили, что у первых двух строк длина 7 символов вместо пяти? Это из-за того, что каждая строка содержит в конце символы переноса строки.

Чаще всего они нам не нужны, поэтому их можно убрать, передав вторым параметром константу FILE_IGNORE_NEW_LINES :

Теперь у всех строк будет по 5 символов.

Если нам необходимо получить только заполненные строки в файле и пропустить пустые, можно передать вторым параметром константу FILE_SKIP_EMPTY_LINES :

Разумеется, мы можем передать сразу две константы:

Создание файла и запись в файл: file_put_contents()

Функция file_put_contents() позволяет создать файл и заполнить его данными.

Первым параметром функция принимает путь к файлу, вторым — строку с данными. Для создания пустого файла нужно передать вторым параметром пустую строку.

Если файла не существует — он будет создан. Если существует — данные в файле будут перезаписаны.

Чтобы не перезаписывать данные, а добавить их в конец файла, нужно передать третьим параметром константу FILE_APPEND :

Также вторым параметром можно передать массив:

Но этот вариант не очень удобен, поскольку все элементы массива запишутся подряд, без каких-либо разделителей. Чтобы их добавить, можно использовать функцию implode:

Создание папки или структуры папок

Создать папку можно с помощью функции mkdir() (make directory):

Вторым параметром указываются права доступа к файлу в виде восьмеричного числа, по-умолчанию это 0777 , что означает самые широкие права. Для Windows этот аргумент игнорируется.

Кроме этого, второй параметр может игнорироваться при заданной umask (пользовательская маска (user mask), которая нужна для определения конечных прав доступа). В этом случае принудительно сменить права можно функцией chmod() :

Также мы можем создать структуру папок рекурсивно, для этого нужно третьим параметром передать true :

Читайте также:  Php insert all fields

Но в этом случае права доступа будут заданы только для конечной папки. Для изменения прав у каждой из папок придётся указывать права вручную:

Права доступа — это отдельная объёмная тема, поэтому сейчас мы её пока рассматривать не будем.

Проверка существования файла или папки

Проверить существование папки или файла можно с помощью функции file_exists() :

Если вы хотите проверить существование только папки или только файла, для этого есть специальные функции is_dir() и is_file() :

Проверка прав доступа

Функции is_readable() и is_writable() проверяют, есть ли у пользователя, от имени которого запущен PHP, права на чтение и запись файла или папки:

Копирование, перенос и удаление файла

Для удаления файлов используется функция unlink() :

Чтобы скопировать файл, используем функцию copy() :

Для переименования и переноса файла в другую папку используется функция rename() :

Работа с файлами с помощью fopen()

Функций file() , file_get_contents() и file_put_contents() достаточно для решения большинства задач, связанных с управлением файлами.

Но иногда возникают ситуации, когда нам необходимы более продвинутые инструменты. Например, если у нас есть большой текстовый файл и мы хотим читать его построчно, а не весь сразу, для экономии оперативной памяти.

Итак, открыть (или создать и открыть) файл можно с помощью функции fopen() :

Функция fopen() возвращает так называемый лескриптор. Это ссылка, указатель на файл, его мы будем передавать в другие функции. Кстати, тип данных этого дескриптора — resource .

Первым параметром мы передаём путь к файлу, вторым — модификатор доступа к файлу. Ниже перечислены наиболее популярные модификаторы:

  • r — открытие для чтения, указатель переходит в начало файла.
  • r+ — открытие для чтения и записи, указатель переходит в начало файла.
  • w — открытие для записи, указатель переходит в начало файла. Если файла нет — создаётся, если есть — очищается от данных.
  • w+ — открытие для чтения и записи, в остальном аналогичен w .
  • a — открытие для записи, указатель переходит в конец файла. Если файла нет — создаётся.
  • a+ — открытие для чтения и записи, в остальном аналогичен a .
  • x — создание и открытие для записи, указатель переходит в начало файла. Если файл существует — PHP покажет ошибку.
  • x+ — создание и открытие для чтения и записи, в остальном аналогичен x .

Указатель — это нечто вроде курсора. Вы можете переместить его в любое место файла, чтобы добавить или отредактировать определённые данные.

Для записи данных в файл существует функция fwrite() . Давайте попробуем создать файл и записать в него какие-нибудь данные:

Заметьте, из-за модификатора w при каждом запуске скрипта данные в файле стираются и добавляются заново. Если модификатор заменить на a , данные будут не перезаписываться, а добавляться в конец файла.

Для построчного чтения файла используется функция fgets() :

При каждом запуске fgets получает следующую строку и возвращает её в $line . Вторым параметром передаётся максимальная длина строки. Это означает, что если строка слишком длинная, она будет обрезана.

Также в PHP существует множество других полезных функций, работающих с дескриптором файла. Почитать о них можно в документации.

Источник

Оцените статью