php edit php file
Работа с файлами на php: открытие, запись, чтение
На самом деле, чем открыть php файл, не является большой проблемой. Бывает труднее открыть бутылку пива, когда находишься посреди леса. Но так думают лишь заядлые программисты. А для новичков поведаем обо всех возможностях php для работы с файлами:
Файлы php
Файлы с расширением php содержат в себе код написанный, на одноименном языке программирования. В отличие от других языков, php является серверным языком программирования. То есть он выполняется на стороне сервера. Поэтому для отладки его кода на клиентской машине должен быть установлен локальный сервер.
Для работы с файлами php используются специальные приложения – программные редакторы. Наиболее распространенными из них являются:
Открытие и закрытие файлов
В php все операции с файлами осуществляются в несколько этапов:
Чтение и запись файлов
Для работы с функцией требуется открытие и закрытие файла. Пример:
Результат аналогичен предыдущему.
Функции для работы с файлами в php позволяют считывать содержимое построчно и посимвольно:
Для записи текстовых данных в файл существует две идентичные функции:
Функции записывают в файл int file строку string string указанной длины int length ( необязательный аргумент ). Пример:
Создание и удаление файлов
Получение информации о файле
Для получения информации о файлах в php используется целый ряд функций:
Simple PHP editor of text files
I have developed a site for a client and he wants to be able to edit a small part of the main page in a backend type of solution. So as a solution, I want to add a very basic editor (domain.com/backend/editor.php) that when you visit it, it will have a textfield with the code and a save button. The code that it will edit will be set to a TXT file.
I would presume that such thing would be easy to code in PHP but google didn’t assist me this time so I am hoping that there might be someone here that would point me to the right direction. Note that I have no experience in PHP programming, only HTML and basic javascript so please be thorough in any reply that you provide.
8 Answers 8
You create a HTML form to edit the text-file’s content. In case it get’s submitted, you update the text-file (and redirect to the form again to prevent F5/Refresh warnings):
You’re basically looking for a similar concept to that of a contact-form or alike.
Apply the same principles from a tutorial like this one and instead of emailing using mail check out the file functions from PHP.net.
What did you Google on then? php write file gives me a few million hits.
As in the manual for fwrite() :
But to be honest, you should first pick up a PHP book and start trying. You have posted no single requirement, other than that you want to post a textfield (textarea I mean?) to a TXT file. This will do:
Note that this exactly matches your description. It doesn’t read the file when printing the form (so every time you want to edit the text, you have to start from scratch), it does not check the input for anything (do you want the user to be able to post HTML?), it has no security check (everyone can access it and alter the file), and in no way it reads the file for display on the page you want.
First thing to do is capture the information, the simplest way to do this would be the use of a HTML Form with a TEXTAREA:
On ‘save.php’ (or wherever) you can easily see the information sent from the form:
To actually create a file, take a look at the fopen/fwrite commands in PHP, another simplistic example:
WARNING: This is an extremely simplistic answer! You will perhaps want to protect your form and your file, or do some different things. All the above will do is write EXACTLY what was posted in the form to a file. If you want to specify different filenames, overwrite, append, check for bad content/spam etc then you’ll need to do more work.
If you have an editor that is publicly accessible and publishes content to a web page then spam protection is a DEFINITE requirement or you will come to regret it!
If you aren’t interested in learning PHP then you should think about getting a professional developer to take care of any coding work for you!
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» ;
Работа с файлами в 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 File: Definition, Explanation, Examples
Web Development Course:
Before you can consider yourself a coding professional, you need to pay attention to the fundamental aspects of PHP. You should know what is a PHP file, how to use it, and, of course, how to edit PHP files yourself.
Contents
PHP File: Main Tips
A Basic PHP File: Example
While this does look very similar to a simple HTML file, there are two things you should note:
We’d also advise you to learn how PHP functions in your web server. To do that, create a simple script as you see below:
Reading a PHP file
As you can see, there are three parameters:
Parameter | Description |
---|---|
path | Required. Defines a path of the file or the directory to check. |
include_path | Optional. Looks for a file in include_path. |
context | Optional. Defines a custom context. |