On systems which differentiate between binary and text files
(i.e. Windows) the file must be opened with 'b' included in
fopen() mode parameter.

Note:

If handle was fopen()ed in
append mode, fwrite()s are atomic (unless the size of
string exceeds the filesystem's block size, on some
platforms, and as long as the file is on a local filesystem). That is,
there is no need to flock() a resource before calling
fwrite(); all of the data will be written without
interruption.

Note:

If writing twice to the file pointer, then the data will be appended to
the end of the file content:

User Contributed Notes 29 notes

After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php's fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.

Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.

This means the example fwrite_stream() code from the docs, as well as all the "helper" functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.

Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.

// you want copy dummy file or send dummy file // it is possible to send a file larger than 4GB and write without FSEEK used is limited by PHP_INT_MAX. it works on a system 32-bit or 64-bit// fwrite and fread non pas de limite de position du pointeur

Some people say that when writing to a socket not all of the bytes requested to be written may be written. You may have to call fwrite again to write bytes that were not written the first time. (At least this is how the write() system call in UNIX works.)

This is helpful code (warning: not tested with multi-byte character sets)

This may save you time: note that neither "binary-safe file write" nor the use of b mode in fopen mean that fwrite can write binary. It can only write strings (or a single character). For example, attempting to write the byte 0x1 using fwrite results in writing the byte value 0x31.

If you wish to write binary values (bits, bytes, integers, etc.), use a statement like fprintf($Res, "%c", 0x1); . This statement will write a byte to the current offset in the file without converting it to a character (in this case, it will write 0x1).

// you want copy dummy file or send dummy file // it is possible to send a file larger than 4GB and write without FSEEK used is limited by PHP_INT_MAX. it works on a system 32-bit or 64-bit// fwrite and fread non pas de limite de position du pointeur

The above script will hang (tested on Windows 7) before it can echo 'done'.

This is due to another 'feature' of our favourite operating system where filenames like prn.xxx, con.xxx, com1.xxx and aux.xxx (with xxx being any filename extension) are Windows reserved device names. Attempts to create/read/write to these files hangs the interpreter.

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.iniOn OS X Server, php.ini is in private/etc/php.ini.defaultcopy 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)

}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 counterfclose ($handle); // Done

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

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 incrementedvalue ( $incr ) it ads it ALONG the old value... so opening the counterpage about 5 times will make your hits number look like this012131214121312151.21312141213E+ .... you get the piont.nasty, isn't it? REMEMBER to open the file with the 'w' mode (truncatethe file to 0). Doing this will clear the file content and it will make sure thatyour counter works nice. This is the final code

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 appendingecho "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 counterfclose ($handle); // Done?>