PHP: file_put_contents - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

file file_get_contents

Last updated: Fri, 26 Jan 2007

view this page in

# file_put_contents

(PHP 5)

file_put_contents -- Записать строку в файл

## Описание

int file_put_contents ( string filename, mixed data [, int flags [, resource context]] )

Функция идентична последовательному вызову функций fopen(), fwrite() и fclose(). Возвращаемым функцией значением является количество записанных в файл байтов.

Параметр `flags` может принимать значение `FILE_USE_INCLUDE_PATH` и/или `FILE_APPEND`. Используйте `FILE_USE_INCLUDE_PATH` с осторожностью.

Также вы можете передать (одномерный) массив в качестве параметра `data`. Это будет эквивалентно вызову `file_put_contents($filename, join('', $array))`.

Начиная с версии PHP 5.1.0, вы также можете передавать ресурс потока в качестве аргумента `data`. В результате оставшийся буфер этого потока будет скопирован в указанный файл. Это похоже на использование stream_copy_to_stream().

> Замечание: Эта функция безопасна для обработки данных в двоичной форме.

> Подсказка: Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция "fopen wrappers". Смотрите более подробную информацию об определении имени файла в описании функции fopen(), а также список поддерживаемых протоколов URL в Прил. M.

См.также описания функций fopen(), fwrite(), fclose() и file_get_contents().

add a note User Contributed Notes
file_put_contents
llinear
15-Feb-2007 10:41
`If you want to append data to a file using a lock use the following
file_put_contents ('sample.txt', 'some data', FILE_APPEND | LOCK_EX);`
Curtis
21-Dec-2006 03:20
`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:
<?php
if ( !function_exists('file_put_contents') && !defined('FILE_APPEND') ) {
...
}
?>
Also, if the file could not be accessed for writing, the function should return boolean false, not 0. An error is different from 0 bytes written, in this case.`
egingell at sisna dot com
23-Jul-2006 04:11
`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.
<?
define('FILE_APPEND', 1);
function file_put_contents($n, $d, $flag = false) {
$mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
$f = @fopen($n, $mode);
if ($f === false) {
return 0;
} else {
if (is_array($d)) $d = implode($d);
$bytes_written = fwrite($f, $d);
fclose($f);
return $bytes_written;
}
}
?>`
16-Jul-2006 01:24
`simple function for php4:
function file_put_contents($n,$d) {
$f=@fopen($n,"w");
if (!$f) {
return false;
} else {
fwrite($f,$d);
fclose($f);
return true;
}
}`
sendoshin at awswan dot com
05-Mar-2006 11:01
`To clear up what was said by pvenegas+php at gmail dot com on 11-Oct-2005 08:13, file_put_contents() will replace the file by default. Here's the complete set of rules this function follows when accessing a file:
1. Was FILE_USE_INCUDE_PATH passed in the call? If so, check the include path for an existing copy of *filename*.
2. Does the file already exist? If not, first create it in the current working directory. Either way, open the file.
3. Was LOCK_EX passed in the call? If so, lock the file.
4. Was the function called with FILE_APPEND? If not, clear the file's contents. Otherwise, move to the end of the file.
5. Write *data* into the file.
6. Close the file and release any locks.
If you don't want to completely replace the contents of the file you're writing to, be sure to use FILE_APPEND (same as fopen() with 'a') in the *flags*. If you don't, whatever used to be there will be gone (fopen() with 'w').
Hope that helps someone (and that it makes sense ^^)!
- Sendoshin`
pvenegas+php at gmail dot com
11-Oct-2005 07:13
`Note that if the specified file already exists, this function effectively discards its contents (equivalent to fopen with 'w') and inserts the new data. The documentation doesn't say this explicitly, so this might help those who are unsure.`
Jared Kuolt
04-Mar-2005 12:14
`Note that this function will create the file if it does not exists, assuming PHP has write access to the folder.`
aidan at php dot net
20-May-2004 07:11
`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:
http://pear.php.net/package/PHP_Compat`
add a note
file file_get_contents

Last updated: Fri, 26 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST