PHP
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, 10 Oct 2008

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() を続けてコールしてデータをファイルに書き込むのと等価です。

filename が存在しない場合はファイルを作成します。 存在する場合はそのファイルを上書きします。ただし FILE_APPEND フラグが設定されている場合は別です。

パラメータ

filename

データを書き込むファイルへのパス。

data

書き込むデータ。文字列, 配列 もしくは ストリーム リソース (上述) のいずれかを指定可能です。

dataストリーム リソースの場合は、 ストリームのバッファに残っている内容が指定したファイルにコピーされます。 これは、stream_copy_to_stream() の挙動と似ています。

data に一次元の配列を指定することもできます。この場合は file_put_contents($filename, implode('', $array)) と同じ意味になります。

flags

flags の値は、以下のフラグを組み合わせたものとなります (組み合わせ方には多少制限があります)。組み合わせる際には、論理 OR (|) 演算子で連結します。

使用できるフラグ
フラグ 説明
FILE_USE_INCLUDE_PATH filename をインクルードディレクトリから探します。 詳細な情報は include_path を参照ください。
FILE_APPEND filename がすでに存在する場合に、 データをファイルに上書きするするのではなく追記します。
LOCK_EX 書き込み処理中に、ファイルに対する排他ロックを確保します。
FILE_TEXT data をテキストモードで書き込みます。 unicode が有効な場合、デフォルトのエンコーディングは UTF-8 です。 別のエンコーディングを指定するには、 独自のコンテキストを作成するか、あるいは stream_default_encoding() でデフォルトを変更します。 このフラグは FILE_BINARY と同時に使用することはできません。 このフラグは PHP 6 以降でのみ使用可能です。
FILE_BINARY data をバイナリモードで書き込みます。これはデフォルトの設定で、 FILE_TEXT と同時に使用することはできません。 このフラグは PHP 6 以降でのみ使用可能です。

context

stream_context_create() で作成したコンテキストリソース。

返り値

この関数はファイルに書き込まれたバイト数を返します。 あるいは失敗した場合には FALSE を返します。

変更履歴

バージョン 説明
5.0.0 コンテキストがサポートされるようになりました。
5.1.0 LOCK_EX のサポートが追加され、 data パラメータにストリームリソースを指定することが可能になりました。
6.0.0 FILE_TEXT および FILE_BINARY がサポートされるようになりました。

注意

注意: この関数はバイナリデータに対応しています。

ヒント

fopen wrappers が有効の場合、この関数のファイル名として URL を使用することができます。ファイル名の指定方法に関する詳細は fopen()、サポートされる URL プロトコルの種類 については、(例えば)サポートされるプロトコル/ラッパー を参照してください。



file> <file_get_contents
Last updated: Fri, 10 Oct 2008
 
add a note add a note User Contributed Notes
file_put_contents
admin at nabito dot net
04-Aug-2008 01:11
This is example, how to save Error Array into simple log file

<?php

$error
[] = 'some error';
$error[] = 'some error 2';

@
file_put_contents('log.txt',date('c')."\n".implode("\n", $error),FILE_APPEND);

?>
TrentTompkins at gmail dot com
02-Jul-2008 05:25
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.

<?php
   
function file_force_contents($dir, $contents){
       
$parts = explode('/', $dir);
       
$file = array_pop($parts);
       
$dir = '';
        foreach(
$parts as $part)
            if(!
is_dir($dir .= "/$part")) mkdir($dir);
       
file_put_contents("$dir/$file", $contents);
    }
?>
Anonymous
02-May-2008 11:06
file_put_contents() will cause concurrency problems - that is, it doesn't write files atomically (in a single operation), which sometimes means that one php script will be able to, for example, read a file before another script is done writing that file completely.

The following function was derived from a function in Smarty (http://smarty.php.net) which uses rename() to replace the file - rename() is atomic on Linux.

On Windows, rename() is not currently atomic, but should be in the next release. Until then, this function, if used on Windows, will fall back on unlink() and rename(), which is still not atomic...

<?php

define
("FILE_PUT_CONTENTS_ATOMIC_TEMP", dirname(__FILE__)."/cache");
define("FILE_PUT_CONTENTS_ATOMIC_MODE", 0777);

function
file_put_contents_atomic($filename, $content) {
  
   
$temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp');
    if (!(
$f = @fopen($temp, 'wb'))) {
       
$temp = FILE_PUT_CONTENTS_ATOMIC_TEMP . DIRECTORY_SEPARATOR . uniqid('temp');
        if (!(
$f = @fopen($temp, 'wb'))) {
           
trigger_error("file_put_contents_atomic() : error writing temporary file '$temp'", E_USER_WARNING);
            return
false;
        }
    }
  
   
fwrite($f, $content);
   
fclose($f);
  
    if (!@
rename($temp, $filename)) {
        @
unlink($filename);
        @
rename($temp, $filename);
    }
  
    @
chmod($filename, FILE_PUT_CONTENTS_ATOMIC_MODE);
  
    return
true;
  
}

?>
the geek man at hot mail point com
03-Jan-2008 03:23
I use the following code to create a rudimentary text editor. It's not fancy, but then it doesn't have to be. You could easily add a parameter to specify a file to edit; I have not done so to avoid the potential security headaches.

There are still obvious security holes here, but for most applications it should be reasonably safe if implemented for brief periods in a counterintuitive spot. (Nobody says you have to make a PHP file for that purpose; you can tack it on anywhere, so long as it is at the beginning of a file.)

<?php
$random1
= 'randomly_generated_string';
$random2 = 'another_randomly_generated_string';
$target_file = 'file_to_edit.php';
$this_file = 'the_current_file.php';

if (
$_REQUEST[$random1] === $random2) {
    if (isset(
$_POST['content']))
       
file_put_contents($target_file, get_magic_quotes_qpc() ? stripslashes($_POST['content']) : $_POST['content']);
   
    die(
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Editing...</title>
    </head>
    <body>
        <form method="post" action="'
. $this_file . '" />
        <input type="hidden" name="'
. $random1 . '" value="' . $random2 . '" />
        <textarea name="content" rows="50" cols="100">'
. file_get_contents($target_file) . '</textarea><br />
        <input type="submit" value="Save Changes" />
        </form>
    </body>
</html>'
);
}
?>

Then simply browse to hxxp://www.example.com/{$this_file}?{$random1}={$random2}, with the appropriate values substituted for each bracketed variable. Please note that this code assumes the target file to be world writable (-rw-rw-rw- or 666) and will fail to save properly without error if it is not.

Once again, this is by no means secure or permanent, but as a quick fix for brief edits to noncritical files it should be sufficient, and its small size is a definite bonus.
egingell at sisna dot com
20-Dec-2007 07:15
There is a better way. www.php.net/touch

Since you're not adding anything to the file,

<?php
function updateFile($filename) {
    if (!
file_exists($filename)) return;
   
touch($filename);
}
?>
me at briandichiara dot com
04-Oct-2007 12:20
I was in need of a function that updated the last modified date in a php file. There may be a better way, but this is how I did it:

<?php
function updateFile($modFile){
    if(!empty(
$modFile)){
        if(
$fo = fopen($modFile, 'r')){
           
$source = '';
            while (!
feof($fo)) {
              
$source .= fgets($fo);
            }
           
file_put_contents($modFile,$source);
           
fclose($fo);
        }
    }
}
?>
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;
    }
}

?>
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
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> <file_get_contents
Last updated: Fri, 10 Oct 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites