In response to below's corrections etc.. make note that special character such as \n and \r are not recognized as special characters when in the 'single quotes'. You need to use "double quotes."
So:
replace
if(fwrite($handle,$logMessage.'\r\n')===FALSE)
with
if(fwrite($handle,$logMessage."\r\n")===FALSE)
fwrite
(PHP 4, PHP 5)
fwrite — バイナリセーフなファイル書き込み処理
説明
int fwrite ( resource $handle, string $string [, int $length] )fwrite()はstringの内容を handleが指しているファイル・ストリームに書き込み ます。lengthパラメータが与えられている場合、 lengthバイト数分の書き込みが完了したか、 stringが終わりに達したかのいずれか早い方の 事象により書き込みは中止されます。
fwrite() は、 書き込んだバイト数、またはエラー時に FALSE を返します。
length パラメータが指定されている場合、 magic_quotes_runtime 構成オプションは無視され、stringからの スラッシュ文字の取り除きは行われないことに注意してください。
注意: (Windowsのように)バイナリとテキストファイルの形式が異なるシステムにおいては、ファイルをオープンする際に fopen()の mode パラメータに 'b' を指定する必要があります。
注意: fopen() を使用して追記モードでオープンした handle の場合、 fwrite() はアトミックになります (ただし、一部のプラットフォームにおいて string がファイルシステムのブロックサイズを超えない場合、 そしてローカルファイルシステム上のファイルである場合に限ります)。 アトミックであるとは、つまり fwrite() をコールする前にリソースを flock() する必要がないということです。データの書き込みが中断されることはありません。
例 633. 簡単な fwrite() の例
<?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";
}
?>
fread()、 fopen()、 fsockopen()、 popen() および file_put_contents() も参照ください。
fwrite
05-Aug-2007 11:51
19-Jun-2007 05:24
This is an extension / reply to the previous posting by chaobreederxl at gmail dot com:
Creating a text file (.txt) would probably be more useful in the end than an html file. In addition to being harder to parse using PHP than the .txt file, the html would not be formed properly (missing <head> tags, opening and closing <html> tags, etc.) and may not actually display rendered html code in some browsers.
To create a text file that is compatible with both unix and windows platforms, call the fopen and fwrite functions like this:
$today = date("Y_M_j");
$logfile = $today."_log.txt";
$dir = 'logs';
$saveLocation=$dir . '/' . $logfile;
if(!is_dir($dir))
{
mkdir($dir,"0755");
}
if (!$handle = fopen($saveLocation, "a"))
{
//ERROR, DO SOMETHING
exit;
}
else
{
if(fwrite($handle,$logMessage.'\r\n')===FALSE)
{
//ERROR, DO SOMETHING
exit;
}
fclose($handle);
}
I did some minor error handling here just to show how that could be setup. I also added the "\r\n" newline chars. The \r part is specifically meant for windows compatibility, but does not display improperly in unix based systems. I also only used the "a" option on fopen, because "a+" is meant for both reading and writing, and we are only going to be writing in this example.
I have a description of a script similar to this, with a little more detail, at http://www.ebrueggeman.com/php_site_access_log.php if interested.
Hope this helps ~ Elliott
30-Mar-2007 04:52
This is a simple function I wrote that uses the fopen and fwrite functions to log the actions of users... very useful for tracking your members on your site.
<?php
function loguser($reason,$ext = "db"){
if(!is_dir("logs")):
mkdir("logs","0493");
endif;
$fp = fopen("logs/".date("m-d-y").".".$ext, "a+");
fwrite($fp, "<strong>".date("g:i:s A")."</strong>: ".$reason."<br/>");
}
?>
To use this, just call the function like so:
<? loguser($_SERVER["REMOTE_ADDR"]." attempted to create another account.","html"); ?>
The second parameter can be changed to anything that would support HTML. If you leave out the second extension, then it automatically uses the .db extension, which works excellent for me.
Hope this helps.
Paul
09-Mar-2007 08:09
For those who, like me, lost a lot of minutes (hours) to understand why fwrite doesn't create a real utf-8 file, here's the explanation I've found :
I tried to do something like this :
<?php
$myString = utf8_encode("Test with accents éèàç");
$fh=fopen('test.xml',"w");
fwrite($fh,$myString);
fclose($fh);
?>
For a mysterious reason, the resulted file shows the accent without the utf-8 conversion.
I tried the binary, mode, etc. etc. And finally I've found it :
It seems that fwrite NEEDS to have the utf8_encode function INSIDE its parameters like this, to understand it must create a non-text only file :
<?php
$myString = "Test with accents éèàç";
$fh=fopen('test.xml',"w");
fwrite($fh,utf8_encode($myString));
fclose($fh);
?>
Hope this will help
11-Sep-2006 04:08
Use this to get a UTF-8 Unicode CSV file that opens properly in Excel:
$tmp = chr(255).chr(254).mb_convert_encoding( $tmp, 'UTF-16LE', 'UTF-8');
$write = fwrite( $filepath, $tmp );
Use a tab character, not comma, to seperate the fields in the $tmp.
Credit for this goes to someone called Eugene Murai, I found this solution by him after searching for several hours.
19-Mar-2006 04:49
To write a specific byte into a file (let's,say 0000 0001), use the function chr().
<?php
fputs($fp,chr(0x01),1);
?>
24-Jul-2005 06:40
[Editor's Note: No, you only need to use this if you want a BOM (Byte order mark) added to the document - most people do not.]
if you have to write a file in UTF-8 format, you have to add an header to the file like this :
<?php
$f=fopen("test.txt", "wb");
$text=utf8_encode("a!");
// adding header
$text="\xEF\xBB\xBF".$text;
fputs($f, $text);
fclose($f);
?>
07-Jul-2005 12:09
I could'nt quite get MKP Dev hit counter to work.... this is how I modified it
<?
function hitcount()
{
$file = "counter.txt";
if ( !file_exists($file)){
touch ($file);
$handle = fopen ($file, 'r+'); // Let's open for read and write
$count = 0;
}
else{
$handle = fopen ($file, 'r+'); // Let's open for read and write
$count = fread ($handle, filesize ($file));
settype ($count,"integer");
}
rewind ($handle); // Go back to the beginning
/*
* Note that we don't have problems with 9 being fewer characters than
* 10 because we are always incrementing, so we will always write at
* least as many characters as we read
**/
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done
return $count;
}
?>
08-Jun-2005 01:02
To write 'true binary' files combine with pack() :
$a = 65530;
$fp = fopen('test.dat', 'w');
fwrite($fp, pack('L', $a));
fclose($fp);
12-May-2005 09:25
bluevd at gmail dot com mentioned a hit counter. In his/her implementation, the file is first opened, read, closed, then opened +truncated, then written, and closed again. An alternative to this is:
<?php
$file = 'counter.txt or whatever';
$handle = fopen ($file, 'r+'); // Let's open for read and write
$count = int (fread ($handle, filesize ($file)));
// We don't want to think it's a string and try appending
echo "Number of hits $count";
rewind ($handle); // Go back to the beginning
/*
* Note that we don't have problems with 9 being fewer characters than
* 10 because we are always incrementing, so we will always write at
* least as many characters as we read
**/
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done
?>
25-Mar-2005 11:24
Using fwrite to write to a file in your include folder...
PHP does not recognise the permissions setting for the file until you restart the server... this script works fine. (still have to create the blank text file first though...it is not created automatically) On OS X Server..
Using the 1 in fopen tells php to look for the file in your include folder. Change your include folder by altering include_path in php.ini
On OS X Server, php.ini is in private/etc/php.ini.default
copy the file and call it php.ini
the default include path is usr/lib/php
(All these folders are hidden - use TinkerTool to reveal them)
<?php
$file = fopen('textfile.txt', 'a', 1);
$text="\n Your text to write \n ".date('d')."-".date('m')."-".date('Y')."\n\n";
fwrite($file, $text);
fclose($file);
?>
18-Feb-2005 05:15
difficulty appending to file in SAFE MODE ON
if you are getting resource errors etc try this...
$textline="whatever string you submitted or created";
$filename="afilename.log"; // or whatever your path and filename
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)"; // or handle your error
exit; }
$textline.="\n"; // dont forget that period
// now write content to our opened file.
IF (fwrite($handle,$textline) === FALSE)
{echo "Cannot write to file ($filename)";// or handle your error
exit;}
echo "Success, wrote ($textline) to file ($filename)";
fclose($handle);
10-Feb-2005 02:55
if you want to create quickly and without fopen use system, exec
system('echo "blahblah" > /path/file');
04-Feb-2005 04:27
I needed to append, but I needed to write on the file's beginning, and after some hours of effort this worked for me:
$file = "file.txt";
if (!file_exists("file.txt")) touch("file.txt");
$fh = fopen("file.txt", "r");
$fcontent = fread($fh, filesize("file.txt"));
$towrite = "$newcontent $fcontent";
$fh22 = fopen('file.txt', 'w+');
fwrite($fh2, $towrite);
fclose($fh);
fclose($fh2);
23-Dec-2004 02:56
Watch out for mistakes in writting a simple code for a hit counter:
<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
//echo $incr;
$incr++;
fclose($cont);
$cont=fopen('cont.txt','a');
fwrite($cont,$incr);
fclose($cont);
?>
Why? notice the second fopen -> $cont=fopen('cont.txt','a');
it opens the file in writting mode (a). And when it ads the incremented
value ( $incr ) it ads it ALONG the old value... so opening the counter
page about 5 times will make your hits number look like this
012131214121312151.21312141213E+ .... you get the piont.
nasty, isn't it? REMEMBER to open the file with the 'w' mode (truncate
the file to 0). Doing this will clear the file content and it will make sure that
your counter works nice. This is the final code
<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
//echo $incr;
$incr++;
fclose($cont);
$cont=fopen('cont.txt','w');
fwrite($cont,$incr);
fclose($cont);
?>
Notice that this work fine =)
XU (alias Iscu Andrei)
27-Oct-2004 07:32
In PHP 4.3.7 fwrite returns 0 rather than false on failure.
The following example will output "SUCCESS: 0 bytes written" for existing file test.txt:
$fp = fopen("test.txt", "rw");
if (($bytes_written = fwrite($fp, "This is a test")) === false) {
echo "Unable to write to test.txt\n\n";
} else {
echo "SUCCESS: $bytes_written bytes written\n\n";
}
22-Aug-2003 07:04
Hope this helps other newbies.
If you are writing data to a txt file on a windows system and need a line break. use \r\n . This will write hex OD OA.
i.e.
$batch_data= "some data... \r\n";
fwrite($fbatch,$batch_data);
The is the equivalent of opening a txt file in notepad pressing enter and the end of the line and saving it.
17-Jul-2003 06:32
[Ed. Note:
The runtime configuration setting auto_detect_line_endings should solve this problem when set to On.]
I figured out problems when writing to a file using \r as linebreak, after that file() wasn't able to read the data from that file.
Using \n solved the problem.
20-Jun-2003 06:36
the fwrite output striped the slashes if without length argument given, example:
<?php
$str = "c:\\01.txt";
$out = fopen("out.txt", "w");
fwrite($out, $str);
fclose($out);
?>
the out.txt will be:
c:^@1.txt
the '\\0' without escape will be '\0' ==> 0x00.
the correct one is change fwrite to:
fwrite($out, $str, strlen($str));
05-Jun-2003 03:35
Use caution when using:
$content = fread($fh, filesize($fh)) or die "Error Reading";
This will cause an error if the file you are reading is zero length.
Intead use:
if ( false === fread($fh, filesize($fh)) ) die "Error Reading";
Thus it will be successful on reading zero bytes but detect and error returned as FALSE.
19-May-2003 07:12
Don't forget to check fwrite returns for errors! Just because you successfully opened a file for write, doesn't always mean you can write to it.
On some systems this can occur if the filesystem is full, you can still open the file and create the filesystem inode, but the fwrite will fail, resulting in a zero byte file.
10-Feb-2003 03:33
[[Editors note: There is no "prepend" mode, you must essentially rewrite the entire file after prepending contents to a string. Perhaps you will use file(), modify, implode(), then fopen()/fwrite() it back]]
To put strings into the front of the file, you need to set place the pointer at the top of the file when openning the file with fopen(), see fopen() for more info.