downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

glob> <ftruncate
[edit] Last updated: Fri, 04 May 2012

view this page in

fwrite

(PHP 4, PHP 5)

fwriteÉcrit un fichier en mode binaire

Description

int fwrite ( resource $handle , string $string [, int $length ] )

fwrite() écrit le contenu de la chaîne string dans le fichier pointé par handle.

Liste de paramètres

handle

Un pointeur de système de fichiers de type resource qui est habituellement créé en utilisant la fonction fopen().

string

La chaîne à écrire.

length

Si la longueur length est fournie, l'écriture s'arrêtera après length octets, ou à la fin de la chaîne (le premier des deux).

Notez que si length est fourni, alors l'option de configuration magic_quotes_runtime sera ignorée, et les slash seront conservés.

Valeurs de retour

fwrite() retourne le nombre d'octets écrits, ou FALSE si une erreur survient.

Notes

Note:

Le fait d'écrire dans un flux peut se termine avant que la chaîne complète ne soit écrite. La valeur retournée par la fonction fwrite() peut être vérifiée comme ceci :

<?php
function fwrite_stream($fp$string) {
    for (
$written 0$written strlen($string); $written += $fwrite) {
        
$fwrite fwrite($fpsubstr($string$written));
        if (
$fwrite === false) {
            return 
$fwrite;
        }
    }
    return 
$written;
}
?>

Note:

Sur les systèmes qui font la différence entre les fichiers binaires et les fichiers textes (par exemple, Windows), le fichier doit être ouvert avec l'option 'b' inclus dans le paramètre de mode de fopen().

Note:

Si handle est ouvert en mode ajout (append), fwrite() sera atomique (sauf si la taille de string excède la taille du bloc du système de fichiers, sur quelques plates-formes, et tant que le fichier se trouve sur le système de fichiers local). Ainsi, il n'est pas nécessaire d'utiliser la fonction flock() sur une ressource avant d'appeler la fonction fwrite() ; toutes les données seront écrites sans interruption.

Note:

Si l'on écrit 2 fois dans le fichier, les données seront ajoutées à la fin du fichier ; cela signifie que l'exemple suivant ne donnera pas le résultat attendu :

<?php
$fp 
fopen('data.txt''w');
fwrite($fp'1');
fwrite($fp'23');
fclose($fp);

// le contenu de 'data.txt' est maintenant 123 et non 23 !
?>

Exemples

Exemple #1 Exemple avec fwrite()

<?php
$filename 
'test.txt';
$somecontent "Ajout de chaîne dans le fichier\n";

// Assurons nous que le fichier est accessible en Ã©criture
if (is_writable($filename)) {

    
// Dans notre exemple, nous ouvrons le fichier $filename en mode d'ajout
    // Le pointeur de fichier est placé Ã  la fin du fichier
    // c'est là que $somecontent sera placé
    
if (!$handle fopen($filename'a')) {
         echo 
"Impossible d'ouvrir le fichier ($filename)";
         exit;
    }

    
// Ecrivons quelque chose dans notre fichier.
    
if (fwrite($handle$somecontent) === FALSE) {
        echo 
"Impossible d'écrire dans le fichier ($filename)";
        exit;
    }

    echo 
"L'écriture de ($somecontent) dans le fichier ($filename) a réussi";

    
fclose($handle);

} else {
    echo 
"Le fichier $filename n'est pas accessible en Ã©criture.";
}
?>

Voir aussi

  • fread() - Lecture du fichier en mode binaire
  • fopen() - Ouvre un fichier ou une URL
  • fsockopen() - Ouvre un socket de connexion Internet ou Unix
  • popen() - Crée un processus de pointeur de fichier
  • file_get_contents() - Lit tout un fichier dans une chaîne



glob> <ftruncate
[edit] Last updated: Fri, 04 May 2012
 
add a note add a note User Contributed Notes fwrite
pubdc on yahoo 18-Oct-2011 11:48
I have encountered many instances where fwrite will fail to append all text to the file, especially when there is a sequence of fwrite appends.

Sometimes it will work fine, sometimes the file will be only half-written. Adding a usleep(100000) for a tenth-of-a-second pause between the fwrites will usually avoid such issues without imposing too much of a delay.
Jon Haynes 01-Apr-2011 02:48
Be careful of using reserved Windows filenames in fwrite operations.

<?php
$fh
= fopen('prn.txt', 'w');
fwrite($fh, 'wtf?');
echo
'done' . PHP_EOL;
?>

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.
nate at frickenate dot com 24-Mar-2010 09:51
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.

<?php
// BROKEN function - infinite loop when fwrite() returns 0s
function fwrite_stream($fp, $string) {
    for (
$written = 0; $written < strlen($string); $written += $fwrite) {
       
$fwrite = fwrite($fp, substr($string, $written));
        if (
$fwrite === false) {
            return
$written;
        }
    }
    return
$written;
}
?>
chaly 12-Dec-2009 08:47
Here are the two function I use to save my arrays to a file and load them into exactly the same array as it was before.

At the moment I have no need in saving ressources or something. There I guess a memory-dump and -load is needed.

<?php
   
function save_array_to_file($filename,$b)
    {
        if (!
is_resource($filename))
        {
            if (!
$file = fopen($filename,'w+')) return false;
        } else {
           
$file = $filename;
        }
        foreach (
$b as $key=>$val)
        {
           
fwrite($file,(is_int($key) ? chr(6).(string)$key : chr(5).$key));
            if (
is_array($val))
            {
               
fwrite($file,chr(0)); //array starts
               
save_array_to_file($file,$val);
               
fwrite($file,chr(1)); //array ends
           
}
            elseif (
is_int($val))
            {
               
fwrite($file,chr(2).(string) $val); //int
           
}
            elseif (
is_string($val))
            {
               
fwrite($file,chr(3).$val); //string
           
}
        }
        if (!
is_resource($filename)) fclose($file);
        return
true;
    }
    function
read_array_from_file($filename)
    {
        if (!
is_resource($filename))
        {
            if (!
$file = fopen($filename,'r')) return false;
        } else {
           
$file = $filename;
        }
       
$ret=array();
       
$key='';
       
$val=null;
       
$mod=0;
        while (!
feof($file))
        {
           
$b = fread($file,1);
            if (
ord($b) < 9)
            {
                if (
$val!=null)
                {
                    if (
$mod==2) $val=(int) $val;
                    if (
$mod==3) $val=(string) $val;
                   
$ret[$key]=$val;
                   
$key='';
                   
$val=null;
                   
$mod=0;
                } else {
                    if (
ord($b)==0)
                       
$mod=0;
                    elseif (
ord($b)==1)
                        return
$ret;
                    else
                    {
                        if (
$mod==5) $key=(string) $key;
                        if (
$mod==6) $key=(int) $key;
                       
$mod=ord($b);
                    }
                }
            } else {
                if (
$mod==5 || $mod==5)
                   
$key.=$b;
                elseif (
$mod==0)
                   
$val=read_array_from_file($file);
                else
                   
$val.=$b;
            }
        }
        if (!
is_resource($filename)) fclose($file);
        return
$ret;
    }
?>
oktavianus dot programmer at gmail dot com 03-Jun-2009 08:51
this the another sample to use fwrite with create a folder and create the txt file.

<?php
$mypath
="testdir\\subdir\\test";
mkdir($mypath,0777,TRUE);
$filename = $mypath.'\test.txt';
$handle = fopen($filename,"x+");
$somecontent = "Add this to the file Oktavianus";
fwrite($handle,$somecontent);
echo
"Success";
fclose($handle);
?>

please try...
Oktavianus
Anonymous 15-May-2009 09:36
If you write with the pointer in the middle of a file, it overwrites what's there rather than shifting the rest of the file along.
ceo at l-i-e dot com 10-Nov-2008 03:07
If you are trying to write binary/structured data (e.g., a 4-byte sequence for an (int)) to a file, you will need to use:
http://php.net/pack
james at facepwn dot com 09-Oct-2008 05:25
if (is_writable($filename)) {

Could also be

if (is_writable($filename) or die ("Can not write to ".$filename)) {
michael at newbcity dot com 27-May-2008 11:11
For my fellow newbies, if you test the sample script and want to have the .txt file created for you, you need to comment out the is_writable stuff, like this: 

<?php
$filename
= 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
//if (is_writable($filename)) {

// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo
"Cannot open file ($filename)";
exit;
}

// Write $somecontent to our opened file.
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";
//}
?>
kontakt at bmservices dot de 22-May-2008 04:03
Checking if fwrite failed will not work in that way:

if (!fwrite($fH, $myText)) echo "Write error";

because fwrite return the number of bytes written or FALSE in case of an error.

So: if $myText is an empty string, fwrite will return 0, which is interpreted here as "FALSE", although the writing out of the string is ok.

So you should check in that way:

if (@fwrite($fH, $myText)===FALSE) echo "Write error";

Regards from Berlin, Gérôme
elinor_hust at REMOVETHIS dot hotmail dot com 01-Apr-2008 05:26
Remember to use double-quotes when outputting special characters such as \n or they come out literally.

...
dharris dot nospam at removethispart dot drh dot net 20-Feb-2008 10:47
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)

function fwrite_with_retry($sock, &$data)
{
    $bytes_to_write = strlen($data);
    $bytes_written = 0;

    while ( $bytes_written < $bytes_to_write )
    {
        if ( $bytes_written == 0 ) {
            $rv = fwrite($sock, $data);
        } else {
            $rv = fwrite($sock, substr($data, $bytes_written));
        }

        if ( $rv === false || $rv == 0 )
            return( $bytes_written == 0 ? false : $bytes_written );

        $bytes_written += $rv;
    }

    return $bytes_written;
}

Call this like so:

    $rv = fwrite_with_retry($sock, $request_string);

    if ( ! $rv )
        die("unable to write request_string to socket");
    if ( $rv != strlen($request_string) )
        die("sort write to socket on writing request_string");
mesho 15-Jan-2008 02:20
be easy :)), this works fine

<?

$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);

?>
chad 0x40 herballure 0x2e com 05-Sep-2007 10:13
Remember to check the return value of fwrite(). In particular, writing into a socket can return fewer bytes than requested, and you'll have to try again with the remainder of your data.
chaobreederxl at gmail dot com 29-Mar-2007 11: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
cutmaster at fearlesss dot com 09-Mar-2007 03: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
zaccraven at junk.com 11-Sep-2006 12: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.
santibari at yahoo dot com 18-Mar-2006 11:49
To write a specific byte into a file (let's,say 0000 0001), use the function chr().
<?php

fputs
($fp,chr(0x01),1);

?>
bahatest at ifrance doc com 23-Jul-2005 02: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);
?>
james at nicolson dot biz 06-Jul-2005 08: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;
}     
?>
albert;cutthis; at ;coznospam;ribox dot nl 07-Jun-2005 09:02
To write 'true binary' files combine with pack() :

$a = 65530;
$fp = fopen('test.dat', 'w');
fwrite($fp, pack('L', $a));
fclose($fp);
MKP Dev 12-May-2005 05: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
?>
Will at EnigmaChannel dot com 25-Mar-2005 06: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);
?>
goodwork at myrealbox dot com 17-Feb-2005 12: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);
sheyh 09-Feb-2005 09:55
if you want to create quickly and without fopen use system, exec

system('echo "blahblah" > /path/file');
kzevian at cybercable dot net dot mx 03-Feb-2005 11: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);
bluevd at gmail dot com 22-Dec-2004 09: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)
chill at cuna dot org 26-Oct-2004 03: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";
}
php at biggerthanthebeatles dot com 21-Aug-2003 03: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.
Andi 17-Jul-2003 02: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.
chedong at hotmail dot com 20-Jun-2003 02: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));
Jake Roberts 04-Jun-2003 11: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.
Chris Blown 19-May-2003 03: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.
seeker at seek dot planet 09-Feb-2003 10: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.

 
show source | credits | sitemap | contact | advertising | mirror sites