update : 2015.11.03
php.shukuma.com

검색:
 
 
Write a string to a file

file_put_contents

(PHP 5, PHP 7)

file_put_contentsWrite a string to a file

설명

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

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

인수

filename

Path to the file where to write the data.

data

The data to write. Can be either a string, an array or a stream resource.

If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

You can also specify the data parameter as a single dimension array. This is equivalent to file_put_contents($filename, implode('', $array)).

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Available flags
Flag Description
FILE_USE_INCLUDE_PATH Search for filename in the include directory. See include_path for more information.
FILE_APPEND If file filename already exists, append the data to the file instead of overwriting it.
LOCK_EX Acquire an exclusive lock on the file while proceeding to the writing. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x".

context

A valid context resource created with stream_context_create().

반환값

This function returns the number of bytes that were written to the file, or FALSE on failure.

Warning

이 함수는 논리 FALSE를 반환하지만, 논리 FALSE로 취급할 수 있는 다른 값을 반환할 수 있습니다. 자세한 정보는 논리형 섹션을 참고하십시오. 이 함수의 반환값을 확인하려면 === 연산자를 이용하십시오.

예제

Example #1 Simple usage example

<?php
$file 
'people.txt';
// Open the file to get existing content
$current file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file$current);
?>

Example #2 Using flags

<?php
$file 
'people.txt';
// The new person to add to the file
$person "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file$personFILE_APPEND LOCK_EX);
?>

변경점

버전 설명
5.1.0 Added support for LOCK_EX and the ability to pass a stream resource to the data parameter

주의

Note: 이 함수는 바이너리 안전입니다.

Tip

fopen 래퍼를 활성화하면, 파일명으로 URL을 사용할 수 있습니다. 파일 이름을 지정하는 방법은 fopen()을 참고하십시오. 다양한 래퍼의 기능, 사용법, 제공하는 예약 정의 변수들에 대해서는 Supported Protocols and Wrappers를 참고하십시오.

참고