Filesystem Funcții
PHP Manual

fwrite

(PHP 4, PHP 5, PHP 7)

fwriteBinary-safe file write

Descrierea

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

fwrite() writes the contents of string to the file stream pointed to by handle.

Parametri

handle

O resursă de tip indicator în sistemul de fișiere care este în mod tipic creată utilizând fopen().

string

The string that is to be written.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Valorile întoarse

fwrite() returns the number of bytes written, or FALSE on error.

Note

Notă:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

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

Notă:

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

Notă:

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.

Notă:

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

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

// the content of 'data.txt' is now 123 and not 23!
?>

Exemple

Example #1 A simple fwrite() example

<?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";
}
?>

A se vedea și


Filesystem Funcții
PHP Manual