file_put_contents 文字列をファイルに書き込む
int file_put_contents ( string $filename , mixed $data [, int $flags [, resource $context ]] )
関数file_put_contentsは、PHP5の機能で、PHP4にはない。この関数を使うと、fopen()、fwrite()、 fclose() を続けてコールしてデータをファイルに書き込むのとおなじことができる。PHP4しかサポートしていないサーバがまだ多いので、fopen()、fwrite()、 fclose() で書いておいたほうがいい。
fopen ファイルまたは URL をオープンする
resource fopen ( string $filename , string $mode [, bool $use_include_path [, resource $context ]] )
〔例〕<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>
プロトコルのハンドラ(ラッパーともいう)のサポート、セーフモード、open_basedir有効 、php.iniでのallow_url_fopenなどの状態によっては、URLの書込みオープンができない。w 書込みのみ。 w+ 読み込みと書込み。ファイルポインターを先頭に置く。追加書き込みをするときは、ファイルポインターを終端に置く a または a+ を指定してオープンする。fwrite ― バイナリセーフなファイル書き込み処理
string の内容を handle が指しているファイル・ストリームに書き込みます。int fwrite ( resource $handle , string $string [, int $length ] )
handle - fopen() を使用して作成したファイルシステムポインタリソースstring - 書き込む文字列
〔例1〕文末に文字列を追加する
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// ファイルが存在しかつ書き込み可能かどうか確認します
if (is_writable($filename)) {
// この例では$filenameを追加モードでオープンします。
// ファイルポインタはファイルの終端になりますので
// そこがfwrite()で$somecontentが追加される位置になります。
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// オープンしたファイルに$somecontentを書き込みます
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
〔例2〕カウンタ・ファイル書込み 3117
<?
$file = "counter.txt";
if ( !file_exists($file)){
touch ($file);
$handle = fopen ($file, 'r+');
$str = "<? \$count=0 ?>";
}
else{
include "counter.txt";
$count++;
$str = "<? \$count=".$count." ?>";
$handle = fopen ($file, 'r+');
}
fwrite ($handle, $str);
fclose ($handle);
?>
fclose ― オープンされたファイルポインタをクローズする
bool fclose ( resource $handle )
〔例〕<?php
$handle = fopen('somefile.txt', 'r');
fclose($handle);
?>