- Запись и чтение файлов в PHP
- Сохранение в файл
- File_put_contents:
- Fopen / fwrite:
- Возможные режимы fopen():
- Дописать строку в начало файла
- Дописать строку в конец файла
- Чтение из файла
- Чтение всего файла
- Чтение файла в массив
- Чтение файла сразу в браузер
- Получить первую строку из файла
- Первые три строки из файла:
- Получить последнюю строку из файла
- Последние три строки из файла:
- Запись и чтение массивов в файл
- Serialize
- Запись:
- Чтение:
- JSON
- Запись:
- Чтение:
- PHP save POST data to file – save POST request as json file in server – Works on PHP 7/8
- PHP saves POST data to file
- Creating a PHP file
- Using Terminal
- Using Postman
- Write Post data to file with PHP
Запись и чтение файлов в PHP
Примеры сохранения и чтения текстовых данных и массивов в файлы.
Сохранение в файл
Функция file_put_contents() записывает содержимое переменной в файл, если файла не существует. то пытается его создать, если существует то полностью перезапишет его.
File_put_contents:
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, $text);
Fopen / fwrite:
Набор функций fopen, fwrite, fclose предназначены для более гибкой работы с файлами.
- fopen – открытие или создание файла.
- fwrite – запись данных.
- fclose – закрытие файла.
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'w'); fwrite($fh, $text); fclose($fh);
Возможные режимы fopen():
Mode | Описание |
---|---|
r | Открывает файл только для чтения, помещает указатель в начало файла. |
r+ | Открывает файл для чтения и записи, помещает указатель в начало файла. |
w | Открывает файл только для записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пробует его создать. |
w+ | Открывает файл для чтения и записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пытается его создать. |
a | Открывает файл только для записи, помещает указатель в конец файла. Если файл не существует – пытается его создать. |
a+ | Открывает файл для чтения и записи, помещает указатель в конец файла. Если файл не существует – пытается его создать. |
x | Создаёт и открывает только для записи; помещает указатель в начало файла. Если файл уже существует, вызов fopen() закончится неудачей, вернёт false и выдаст ошибку. Если файл не существует, попытается его создать. |
x+ | Создаёт и открывает для чтения и записи, в остальном имеет то же поведение, что и « x ». |
c | Открывает файл только для записи. Если файл не существует, то он создаётся. Если же файл существует, то он не обрезается (в отличие от « w »), и вызов к этой функции не вызывает ошибку (также как и в случае с « x »). Указатель на файл будет установлен на начало файла. |
c+ | Открывает файл для чтения и записи, в остальном имеет то же поведение, что и « c ». |
Доступно в место fwrite() используют fputs() , разницы ни какой т.к. эта функция является псевдонимом.
Дописать строку в начало файла
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); file_put_contents($filename, $new_str . PHP_EOL . $text);
Дописать строку в конец файла
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, PHP_EOL . $new_str, FILE_APPEND);
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'c'); fseek($fh, 0, SEEK_END); fwrite($fh, PHP_EOL . $new_str); fclose($fh);
Чтение из файла
Чтение всего файла
$filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); echo $text;
$filename = __DIR__ . '/file.txt'; $text = ''; $fh = fopen($filename, 'r'); while (!feof($fh)) < $line = fgets($fh); $text .= $line . PHP_EOL; >fclose($fh); echo $text;
Чтение файла в массив
Функция file() – читает содержимое файла и помещает его в массив, доступны опции:
- FILE_IGNORE_NEW_LINES – пропускать новую строку в конце каждого элемента массива.
- FILE_SKIP_EMPTY_LINES – пропускать пустые строки.
$filename = __DIR__ . '/file.txt'; $array = file($filename); print_r($array);
Чтение файла сразу в браузер
$filename = __DIR__ . '/file.txt'; readfile($filename);
Получить первую строку из файла
$filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'r'); echo fgets($fh); fclose($fh); /* или */ $filename = __DIR__ . '/file.txt'; $array = file($filename); echo $array[0];
Первые три строки из файла:
$filename = __DIR__ . '/file.txt'; $array = file($filename); $first_3 = array_slice($array, 0, 3); print_r($first_3);
Получить последнюю строку из файла
$filename = __DIR__ . '/file.txt'; $array = file($filename); $last = array_slice($array, -1); echo $last[0];
Последние три строки из файла:
$filename = __DIR__ . '/file.txt'; $array = file($filename); $last_3 = array_slice($array, -3); print_r($last_3);
Запись и чтение массивов в файл
Serialize
Не очень удачное хранение данных в сериализованном виде т.к. изменение одного символа может привести к ошибке чтения всех данных в файле. Подробнее в статье «Функция serialize, возможные проблемы»
Запись:
$array = array('foo', 'bar', 'hallo', 'world'); $text = base64_encode(serialize($array)); file_put_contents(__DIR__ . '/array.txt', $text);
Чтение:
$array = unserialize(base64_decode($text)); print_r($array);
JSON
Запись:
$array = array('foo', 'bar', 'hallo', 'world'); $json = json_encode($array, JSON_UNESCAPED_UNICODE); file_put_contents(__DIR__ . '/array.json', $json);
Чтение:
$json = file_get_contents(__DIR__ . '/array.json'); $array = json_decode($json, true); print_r($array);
PHP save POST data to file – save POST request as json file in server – Works on PHP 7/8
PHP save post data to file. Using PHP’s file put contents method, you can store data from a POST request to a file. When using this function, a string of data is written to a file, overwriting any existing data in the file.
PHP saves POST data to file
Here is a straightforward illustration of saving POST data to a text file:
In this example, we first determine whether the request type is a POST request and if it is, we use the $_POST array to get the data from the POST request. The file put contents function is then used to write the data to the file data.txt. The file will be generated if it doesn’t already exist. If it does, its contents will be replaced if they already exist.
It’s crucial to remember that this code creates a plain text file from the data. You might need to employ a different technique if you need to store the data in a different format. Additionally, if the data has to be encrypted or is confidential, the file put contents method might not be appropriate.
It’s crucial to take security considerations like file permissions and access controls into account when saving data to a file on a server. In general, it’s a good idea to keep sensitive information in a secure location and to employ appropriate access controls to restrict who can access and edit the information.
PHP save post data to file – First, get to know the below three features:
- php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP-headers of the request, regardless of the content type.
- file_get_contents() function: This function in PHP is used to read a file into a string.
- json_decode() function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object.
Creating a PHP file
create a PHP file with the following code for (PHP save POST data to file):
http://localhost:8888/web_folder/ index.php
Now you can test the code by requesting through Postman or using terminal
Using Terminal
just run the following command in terminal
curl -i -X PUT -d '' http://localhost:8888/web_folder/index.php
Using Postman
Write Post data to file with PHP
1) In PHP, to get POST data from an incoming request use the $_POST array. The POST array in PHP is associative, which means that each incoming parameter will be a key-value pair. In development it’s helpful to understand what you’re actually getting in $_POST. You can dump the contents using printf() or var_dump() like the following.
2) Choose a useful string-based format for storing the data. PHP has a serialize() function, which you could use to turn the array into a string. It’s also easy to turn the array into a JSON string. I suggest using JSON since it’s natural to use this notation across various languages (whereas using a PHP serialization would somewhat bind you to using PHP in the future). In PHP 5.2.0 and above the json_encode() function is built-in.
$json_string = json_encode($_POST); // For info re: JSON in PHP: // http://php.net/manual/en/function.json-encode.php
3) Store the string in a file. Try using fopen(), fwrite(), and fclose() to write the json string to a file.
$json_string = json_encode($_POST); $file_handle = fopen('my_filename.json', 'w'); fwrite($file_handle, $json_string); fclose($file_handle); // For info re: writing files in PHP: // http://php.net/manual/en/function.fwrite.php
You’ll want to come up with a specific location and methodology to the file paths and file names used.
Note: There’s also the possibility of getting the HTTP request’s POST body directly using $HTTP_RAW_POST_DATA. The raw data will be URL-encoded and it will be a string that you can write to a file as described above.