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().



file_put_contents
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

<file_get_contentsfile>
 Last updated: Mon, 14 Nov 2005