Saving files 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 ».
Читайте также:  Python посчитать время выполнения кода

Доступно в место 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, возможные проблемы»

Читайте также:  Java system error code

Запись:

$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);

Источник

Saving files with PHP scripts in local applications

When run in a desktop application, PHP code can access local files on the end user’s computer, so it is possible to save and modify files locally. To load compiled files, please see this page.

Please refer to the Saving Files topic of the General Demonstration for live demonstrations and further explanation about saving local files with your ExeOutput for PHP apps.

Saving and storing files locally¶

PHP provides you with several ways to load and save files. In order to correctly save files, you must ensure that the user has permissions to write to files into the location you want.

For instance, a portable application is generally started from a USB stick and the folder that contains the EXE has write permissions. Your application will be able to save files in that folder. On the contrary, if your application is installed in the Program Files directory, it is generally not allowed to save files in the application’s folder because of the Windows UAC feature.

Thus, ExeOutput for PHP provides you with a storage folder dedicated to your application. The absolute path to this folder can be retrieved with the following php command:

This folder is always available: you can use it to store the settings of your application. You may customize the name of the storage folder in ExeOutput by going to the «Output -> Output Settings» page.

PHP code: saving a file with fopen / fwrite¶

In compiled applications, you must pass absolute paths to the fopen PHP function.

If you want to let your end users choose the path where the file should be saved, you can display a Save As dialog box.

Источник

How to Write/Save to a File with PHP [Examples]

PHP Write/Save File

This tutorial will demonstrate how to write data to a file on the server in the PHP programming language. Code examples are provided to show you how it’s done.

Writing data to a file server-side is a common task. Whether you’re writing log files so you can debug your app, or saving user submitted data, you will need to save a file at some point in your web development career.

Writing data to a file in PHP is a three-step process. You must first open the file with the fopen() function, and then write to it with the fwrite() function, then close the file resource.

Creating or Opening a File with fopen()

The PHP fopen() function will open a file resource and provide a pointer to that resource which can be used by other functions. If a file does not exist at the path specified, a new file will be created.

fopen() expects both a file path and a mode as parameters – the mode specifies what type of access to the file is required – reading or writing, or both.

Writing/Saving to a File with fwrite()

fwrite() expects two parameters – a file pointer supplied by fopen() and the data to be written.

fwrite() can be called multiple times while a file resource is open to write data to the file sequentially.

Closing a file with fclose()

The fclose() function closes a file pointer, freeing it for use by other processes.

You should always close file pointers when you aren’t using them to reduce the chance of conflicting with other processes which may be trying to read or write to the file.

Examples – Writing Data to Files in PHP

Show often works better than tell, so here is how fopen() and fwrite() are used in combination to write data to a file:

// Assign the file pointer from fopen to the variable $file // Note the write permission requested (w) $file = fopen("test.txt", "w") or die("Cannot open file."); // define the data to be written to the file $data = "Any text data will do.\n"; // Write the data to fhe file with fwrite() fwrite($file, $data); // Write some additional data to the file $data = "More text data to write.\n"; // Write the additional data to the file fwrite($file, $data); // Close the file fclose($file);

Watch Out! Data will be Overwritten!

Be aware that if the file already exists, it will be overwritten by any data called between fopen() and fclose().

Appending Data to a File in PHP

To append to the file instead of overwriting it, use the append (a) mode of fopen(), rather than the write (w) mode:

// Note the append permission requested (a) $file = fopen("test.txt", "a") or die("Cannot open file."); $data = "This will be appended to the end of an existing file.\n"; fwrite($file, $data); fclose($file);

A Note on Permissions

If you receive permission errors you will need to ensure the directory you are running the script from, or the current working directory, are writable by the PHP process. On web servers, this usually means the www-data user will require permission to wread and write.

Источник

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