php make php file
Работа с файлами в PHP
Чтение файла: file_get_contents()
С помощью функции file_get_contents() можно получить содержимое файла:
Также мы можем получить html-код какой-либо страницы в интернете:
Но работает это далеко не для всех сайтов, у многих есть защита от такого примитивного парсинга.
Чтение файла: file()
Функция file() позволяет получить содержимое файла в виде массива. Разделителем элементов является символ переноса строки.
Создадим в корне сайта файл data.txt со следующим содержимым:
Теперь запустим скрипт index.php со следующим кодом:
При запуске этого скрипта мы получим в браузере:
Заметили, что у первых двух строк длина 7 символов вместо пяти? Это из-за того, что каждая строка содержит в конце символы переноса строки.
Чаще всего они нам не нужны, поэтому их можно убрать, передав вторым параметром константу FILE_IGNORE_NEW_LINES :
Теперь у всех строк будет по 5 символов.
Если нам необходимо получить только заполненные строки в файле и пропустить пустые, можно передать вторым параметром константу FILE_SKIP_EMPTY_LINES :
Разумеется, мы можем передать сразу две константы:
Создание файла и запись в файл: file_put_contents()
Функция file_put_contents() позволяет создать файл и заполнить его данными.
Чтобы не перезаписывать данные, а добавить их в конец файла, нужно передать третьим параметром константу FILE_APPEND :
Также вторым параметром можно передать массив:
Но этот вариант не очень удобен, поскольку все элементы массива запишутся подряд, без каких-либо разделителей. Чтобы их добавить, можно использовать функцию implode:
Создание папки или структуры папок
Создать папку можно с помощью функции mkdir() (make directory):
Кроме этого, второй параметр может игнорироваться при заданной umask (пользовательская маска (user mask), которая нужна для определения конечных прав доступа). В этом случае принудительно сменить права можно функцией chmod() :
Также мы можем создать структуру папок рекурсивно, для этого нужно третьим параметром передать true :
Но в этом случае права доступа будут заданы только для конечной папки. Для изменения прав у каждой из папок придётся указывать права вручную:
Проверка существования файла или папки
Проверить существование папки или файла можно с помощью функции file_exists() :
Если вы хотите проверить существование только папки или только файла, для этого есть специальные функции is_dir() и is_file() :
Проверка прав доступа
Функции is_readable() и is_writable() проверяют, есть ли у пользователя, от имени которого запущен PHP, права на чтение и запись файла или папки:
Копирование, перенос и удаление файла
Для удаления файлов используется функция unlink() :
Чтобы скопировать файл, используем функцию copy() :
Для переименования и переноса файла в другую папку используется функция rename() :
Работа с файлами с помощью fopen()
Но иногда возникают ситуации, когда нам необходимы более продвинутые инструменты. Например, если у нас есть большой текстовый файл и мы хотим читать его построчно, а не весь сразу, для экономии оперативной памяти.
Итак, открыть (или создать и открыть) файл можно с помощью функции fopen() :
Для построчного чтения файла используется функция fgets() :
Также в PHP существует множество других полезных функций, работающих с дескриптором файла. Почитать о них можно в документации.
Работа с файлами на php: открытие, запись, чтение
На самом деле, чем открыть php файл, не является большой проблемой. Бывает труднее открыть бутылку пива, когда находишься посреди леса. Но так думают лишь заядлые программисты. А для новичков поведаем обо всех возможностях php для работы с файлами:
Файлы php
Файлы с расширением php содержат в себе код написанный, на одноименном языке программирования. В отличие от других языков, php является серверным языком программирования. То есть он выполняется на стороне сервера. Поэтому для отладки его кода на клиентской машине должен быть установлен локальный сервер.
Для работы с файлами php используются специальные приложения – программные редакторы. Наиболее распространенными из них являются:
Открытие и закрытие файлов
В php все операции с файлами осуществляются в несколько этапов:
Чтение и запись файлов
Для работы с функцией требуется открытие и закрытие файла. Пример:
Результат аналогичен предыдущему.
Функции для работы с файлами в php позволяют считывать содержимое построчно и посимвольно:
Для записи текстовых данных в файл существует две идентичные функции:
Функции записывают в файл int file строку string string указанной длины int length ( необязательный аргумент ). Пример:
Создание и удаление файлов
Получение информации о файле
Для получения информации о файлах в php используется целый ряд функций:
PHP File Create/Write
In this chapter we will teach you how to create and write to a file on the server.
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
The example below creates a new file called «testfile.txt». The file will be created in the same directory where the PHP code resides:
Example
PHP File Permissions
If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.
The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
The example below writes a couple of names into a new file called «newfile.txt»:
Example
If we open the «newfile.txt» file it would look like this:
PHP Overwriting
Now that «newfile.txt» contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file «newfile.txt», and write some new data into it:
Example
If we now open the «newfile.txt» file, both John and Jane have vanished, and only the data we just wrote is present:
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.
Php make php file
(PHP 4, PHP 5, PHP 7, PHP 8)
file — Читает содержимое файла и помещает его в массив
Описание
Читает содержимое файла и помещает его в массив.
Можно также использовать функцию file_get_contents() для получения файла в виде строки.
Список параметров
В качестве необязательного параметра flags может можно указать одну или более следующих констант: FILE_USE_INCLUDE_PATH Ищет файл в include_path. FILE_IGNORE_NEW_LINES Пропускать новую строку в конце каждого элемента массива FILE_SKIP_EMPTY_LINES Пропускать пустые строки
Возвращаемые значения
Каждая строка в полученном массиве будет завершаться символами конца строки, если только не используется FILE_IGNORE_NEW_LINES ).
Замечание: Если у вас возникают проблемы с распознаванием PHP концов строк при чтении или создании файлов на Macintosh-совместимом компьютере, включение опции auto_detect_line_endings может помочь решить проблему.
Ошибки
Примеры
Пример #1 Пример использования file()
// Получает содержимое файла в виде массива. В данном примере мы используем
// обращение по протоколу HTTP для получения HTML-кода с удалённого сервера.
$lines = file ( ‘http://www.example.com/’ );
Примечания
Смотрите также
User Contributed Notes 15 notes
this may be obvious, but it took me a while to figure out what I was doing wrong. So I wanted to share. I have a file on my «c:\» drive. How do I file() it?
Don’t forget the backslash is special and you have to «escape» the backslash i.e. «\\»:
= file ( «C:\\Documents and Settings\\myfile.txt» );
read from CSV data (file) into an array with named keys
. with or without 1st row = header (keys)
(see 4th parameter of function call as true / false)
?>
fuction call with 4 parameters:
?>
PS: also see: http://php.net/manual/de/function.fgetcsv.php to read CSV data into an array
. and other file-handling methods
Be aware that using file() to count lines can cause OOM on the server as it’ll allocate all lines into an array.
If you’re dealing with files that can have thousands of lines, SplFileObject might be a better idea and with little changes you can get the same result.
As of PHP 5.6 the file(), file_get_contents(), and fopen() functions will return false if you are referencing a source URL that doesn’t have a valid SSL certificate. Presumably, you will run into this a lot in your development environments this will drive you crazy.
You will need to create a stream context and provide it as an argument to the various file operations to tell it to ignore invalid SSL credentials.
$args = array(«ssl»=>array(«verify_peer»=>false,»verify_peer_name»=>false),»http»=>array(‘timeout’ => 60, ‘user_agent’ => ‘Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/3.0.0.1’));
(«file()’s problem with UTF-16» is wrong. This is updated.
The former may miss the last line of the string.)
file() seems to have a problem in handling
UTF-16 with or without BOM.
file() is likely to think «\n»=LF (0A) as a line-ending.
So, not only «000A» but also «010A, 020A. FE0A, FF0A. «
are regarded as line-endings.
Moreover, file() causes a serious problem in UTF-16LE.
file() loses first «0A» (the first half of «0A00»)!
And the next line begins with «00» (the rest of «0A00»).
So lines after the first «0A» are totally different.
?>
instead of
$file = file($file_path);
$file_array = file(‘test.txt’); // an empty file
A user suggested using rtrim always, due to the line ending conflict with files that have an EOL that differs from the server EOL.
Using rtrim with it’s default character replacement is a bad solution though, as it removes all whitespace in addition to the ‘\r’ and ‘\n’ characters.
A good solution using rtrim follows:
Here’s my CSV converter
supports Header and trims all fields
Note: Headers must be not empty!
Note: Now that file() is binary safe it is ‘much’ slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:
I did a test on a 200,000 line file. It took seconds with fgets() compared to minutes with file().
This note applies to PHP 5.1.6 under Windows (although may apply to other versions).
It appears that the ‘FILE_IGNORE_NEW_LINES’ flag doesn’t remove newlines properly when reading Windows-style text files, i.e. files whose lines end in ‘\r\n’.
Solution: Always use ‘rtrim()’ in preference to ‘FILE_IGNORE_NEW_LINES’.
file_put_contents
file_put_contents — Пишет данные в файл
Описание
Список параметров
Путь к записываемому файлу.
Значением параметра flags может быть любая комбинация следующих флагов, соединённых бинарным оператором ИЛИ ( | ).
Возвращаемые значения
Функция возвращает количество записанных байт в файл, или false в случае возникновения ошибки.
Примеры
Пример #1 Пример простого использования
Пример #2 Использование флагов
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
User Contributed Notes 36 notes
File put contents fails if you try to put a file in a directory that doesn’t exist. This creates the directory.
It should be obvious that this should only be used if you’re making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.
real 0m3.932s
user 0m2.487s
sys 0m1.437s
real 0m2.265s
user 0m1.819s
sys 0m0.445s
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.
/* the file content */
$content = «this is just a test.» ;
I faced the problem of converting a downloaded csv file that had Windows-1252 encoding, so to convert it to UTF-8 this worked for me:
$from = ‘Windows-1252’;
$to = ‘UTF-8’;
where «$this->path()» has the path of the file. Using this the file is converted from Windows-1252 to UTF-8.
With this you can import it with mysqlimport with no problems.
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
I suggest to expand file_force_contents() function of TrentTompkins at gmail dot com by adding verification if patch is like: «../foo/bar/file»
It’s important to understand that LOCK_EX will not prevent reading the file unless you also explicitly acquire a read lock (shared locked) with the PHP ‘flock’ function.
i.e. in concurrent scenarios file_get_contents may return empty if you don’t wrap it like this:
Make sure not to corrupt anything in case of failure.
__DIR__ is your friend.
In reply to the previous note:
If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.
I can only figure out the FILE_APPEND flag and array support. If I could figure out «resource context» and the other flags, I would include those too.
File put contents fails if you try to put a file in a directory that doesn’t exist. This function creates the directory.
file name including folder.
* example :: /path/to/file/filename.ext or filename.ext
This function doesn’t return False if all data isn’t write, especially when data is a stream resource
I’m updating a function that was posted, as it would fail if there was no directory. It also returns the final value so you can determine if the actual file was written.
As to the previous user note, it would be wise to include that code within a conditional statement, as to prevent re-defining file_put_contents and the FILE_APPEND constant in PHP 5:
file_put_contents() strips the last line ending
If you really want an extra line ending at the end of a file when writing with file_put_contents(), you must append an extra PHP_EOL to the end of the line as follows.
I made a ftp_put_contents function.
//FTP username
$cfg_user = «user» ;
//FTP password
$cfg_pass = «password» ;
//Document Root of FTP
$cfg_document_root = «DOCUMENT ROOT OF FTP» ;
//Link to the website
$cfg_site_link = «Link to the website» ;