- Работа с файлами в PHP
- Чтение файла: file()
- Создание файла и запись в файл: file_put_contents()
- Создание папки или структуры папок
- Проверка существования файла или папки
- Проверка прав доступа
- Копирование, перенос и удаление файла
- Работа с файлами с помощью fopen()
- PHP Create File
- Creating a file using the fopen() function
- Creating a file using the file_put_contents() function
- Summary
- Creating a file in PHP With Examples
- Creating a file using the fopen() function in PHP
- Creating a file using the file_put_contents() function in PHP
- What does file () do in PHP?
- How to create a folder and save it in PHP?
- What is file and directory in PHP?
- How do I run a PHP file?
- How do I edit a PHP file?
- What is the file extension of PHP?
- Related Articles
- Summary
- Leave a Comment Cancel reply
Работа с файлами в 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 :
Но в этом случае права доступа будут заданы только для конечной папки. Для изменения прав у каждой из папок придётся указывать права вручную:
Права доступа — это отдельная объёмная тема, поэтому сейчас мы её пока рассматривать не будем.
Проверка существования файла или папки
Проверить существование папки или файла можно с помощью функции 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 существует множество других полезных функций, работающих с дескриптором файла. Почитать о них можно в документации.
PHP Create File
Summary: in this tutorial, you will learn a couple of ways to create a new file in PHP.
Creating a file using the fopen() function
The fopen() function opens a file. It also creates a file if the file doesn’t exist. Here’s the syntax of the fopen() function:
fopen ( string $filename , string $mode , bool $use_include_path = false , resource $context = ? ) : resource
Code language: PHP (php)
To create a new file using the fopen() function, you specify the $filename and one of the following modes:
Mode | File Pointer |
---|---|
‘w+’ | At the beginning of the file |
‘a’ | At the end of the file |
‘a+’ | At the end of the file |
‘x’ | At the beginning of the file |
‘x+’ | At the beginning of the file |
‘c’ | At the beginning of the file |
‘c+’ | At the beginning of the file |
Except for the ‘a’ and ‘a+’ , the file pointer is placed at the beginning of the file.
If you want to create a binary file, you can append the character ‘b’ to the $mode argument. For example, the ‘wb+’ opens a binary file for writing.
The following example uses fopen() to create a new binary file and write some numbers to it:
$numbers = [1, 2, 3, 4, 5]; $filename = 'numbers.dat'; $f = fopen($filename, 'wb'); if (!$f) < die('Error creating the file ' . $filename); > foreach ($numbers as $number) < fputs($f, $number); >fclose($f);
Code language: HTML, XML (xml)
- First, define an array of five numbers from 1 to 5.
- Second, use the fopen() to create the numbers.dat file.
- Third, use the fputs() function to write each number in the $numbers array to the file.
- Finally, close the file using the fclose() function.
Creating a file using the file_put_contents() function
The file_put_contents() function writes data into a file. Here’s the syntax of the file_put_contents() function:
file_put_contents ( string $filename , mixed $data , int $flags = 0 , resource $context = ? ) : int
Code language: PHP (php)
If the file specified by the $filename doesn’t exist, the function creates the file.
The file_put_contents() function is identical to calling the fopen() , fputs() , and fclose() functions successively to write data to a file.
The following example downloads a webpage using the file_get_contents() function and write HTML to a file:
$url = 'https://www.php.net'; $html = file_get_contents($url); file_put_contents('home.html', $html);
Code language: HTML, XML (xml)
- First, download a webpage https://www.php.net using the file_get_contents() function.
- Second, write the HTML to the home.html file using the file_put_contents() function
Summary
- Use the fopen() function with one of the mode w , w+ , a , a+ , x , x+ , c , c+ to create a new file.
- Use the file_put_contents() function to create a file and write data to it.
- The file_put_contents() function is identical to calling fopen() , fputs() , and fclose() functions successively to write data to a file.
Creating a file in PHP With Examples
In this article, we will be creating a file in PHP in the easiest way with a detailed explanation as well as best program examples. This article is a continuation of the previous topic, entitled PHP File to Array.
In PHP, creating a file can simply be done with the use of fopen() function.
Creating a file using the fopen() function in PHP
The fopen() is a built-in function which is used for creating a file . It sounds a little bit confusing, but in PHP (Hypertext Preprocessor). The same function can create a file and open a files .
fopen ( string $filename , string $mode , bool $use_include_path = false , resource $context = ? ) : resource
For creating a new file with the use of fopen() function we need to specify or declared a $filename and one mode.
TAKE NOTE: If you want to create a ( binary file ), you will need to append the character ‘ b ‘ to an argument name $mode . For example, this ‘ wb +’ automatically opens and close the file for writing a binary.
foreach ($numbers as $number) < fputs($f, $number); >fclose($f); ?>
The program works in this way.
- First, is to define an array which consists of five numbers from 11 to 15.
- Second, the fopen() and fwrite functions should be used to create a numbers.dat file.
- Third, the fputs() function is used to write each number in the array name $numbers to file.
- Lastly, terminate the file with the use of fclose() function.
Creating a file using the file_put_contents() function in PHP
The file_put_contents() is a function which is used to write data into the existing file.
file_put_contents ( string $filename , mixed $data , int $flags = 0 , resource $context = ? ) : int
TAKE NOTE: Once the file upload is showing results of $filename doesn’t exist, the function successfully creates the file.
In addition, if the function returns file_put_contents() is identical when calling the fputs() , fopen() , and fclose() functions sequentially to write data in a file.
- First, the program will download a webpage https://itsourcecode.com/ with the use of function file_get_contents() functions.
- Lastly, the program will write the HTML (HyperText Markup Language) file using the function file_put_contents() .
What does file () do in PHP?
The file() simply works by reading a file into an array. Each element on the array contains a number of lines from the file handling where the newline character is still attached.
How to create a folder and save it in PHP?
In PHP, to create a folder and save, it can simply be done by the function name mkdir() . This is a built-in function that creates a new folder and directory with a specified pathname.
Furthermore, the path and mode are sent as (parameters) to the function mkdir() and it will return TRUE if successful otherwise FALSE if fails.
What is file and directory in PHP?
The file and directory is a set of functions used to retrieve details, update them, and fetch or get information on various system file directories in PHP.
How do I run a PHP file?
The PHP file located inside the ( htdocs ) folder, if you want to execute or run the system, you need to open it in any web browser such as Google Chrome, Mozilla Firefox, and Brave and enter the folder name example “localhost/sample. php” and simply click the enter button.
How do I edit a PHP file?
To edit a file you will need to install a text editor such as VS Code , Sublime Text and any other PHP code editor online.
What is the file extension of PHP?
The file extension of PHP is ( .php ) which need to be put on the end of every file which is similar to a PowerPoint file with a (.ppt) file extension.
Related Articles
Summary
This article tackle in Creating a file, and also tackles Creating a file using the file_put_contents() function, what does file () does, how to create a folder and save it, what is file and directory, how we run a PHP file, how do I edit a PHP file, and what is the file extension.
I hope this lesson has helped you learn PHP a lot. Check out my previous and latest articles for more life-changing tutorials that could help you a lot.
Leave a Comment Cancel reply
You must be logged in to post a comment.