Php open file and write to it

Запись и чтение файлов в 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, возможные проблемы»

Читайте также:  Upload Files to FTP Server in PHP

Запись:

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

Источник

fopen

fopen() binds a named resource, specified by filename , to a stream.

Parameters

If filename is of the form «scheme://. «, it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note:

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers ) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

A list of possible modes for fopen() using mode
mode Description
‘r’ Open for reading only; place the file pointer at the beginning of the file.
‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘w+’ Open for reading and writing; otherwise it has the same behavior as ‘w’ .
‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
‘x’ Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning false and generating an error of level E_WARNING . If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+’ Create and open for reading and writing; otherwise it has the same behavior as ‘x’ .
‘c’ Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’ ), nor the call to this function fails (as is the case with ‘x’ ). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock() ) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
‘c+’ Open the file for reading and writing; otherwise it has the same behavior as ‘c’ .
‘e’ Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

Note:

Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems (Mac OS Classic) used \r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will «look funny».

Windows offers a text-mode translation flag ( ‘t’ ) which will transparently translate \n to \r\n when working with the file. In contrast, you can also use ‘b’ to force binary mode, which will not translate your data. To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.

The default translation mode is ‘b’ . You can use the ‘t’ mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as old versions of notepad. You should use the ‘b’ in all other cases.

If you specify the ‘t’ flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note:

For portability, it is also strongly recommended that you re-write code that uses or relies upon the ‘t’ mode so that it uses the correct line endings and ‘b’ mode instead.

Note: The mode is ignored for php://output , php://input , php://stdin , php://stdout , php://stderr and php://fd stream wrappers.

The optional third use_include_path parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.

Источник

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