fwrite

(PHP 4, PHP 5, PHP 7, PHP 8)

fwriteScrittura su file binary-safe

Descrizione

fwrite(resource $stream, string $data, ?int $length = null): int|false

fwrite() scrive il contenuto di data nello stream del file puntato da stream.

Elenco dei parametri

stream

Un puntatore a una resource di filesystem che è normalmente creata utilizzando fopen().

data

La stringa che deve essere scritta.

length

Se l'argomento length è un int, la scrittura si arresterà dopo aver scritto length byte o alla fine di data a seconda di quale dei due eventi si verifica prima.

Valori restituiti

fwrite() restituisce il numero di byte scritti, o false in caso di fallimento.

Errori/Eccezioni

fwrite() genera un E_WARNING in caso di errore.

Log delle modifiche

Versione Descrizione
8.0.0 Ora length è nullable.

Esempi

Example #1 Un esempio semplice di fwrite()

<?php
$filename
= 'test.txt';
$somecontent = "Aggiungi questo al file\n";

// Assicuriamoci prima che il file esista e sia scrivibile.
if (is_writable($filename)) {

// Nel nostro esempio stiamo aprendo $filename in modalità append.
// Il puntatore del file si trova in fondo al file, quindi
// è lì che $somecontent verrà scritto quando lo scriviamo con fwrite().
if (!$fp = fopen($filename, 'a')) {
echo
"Impossibile aprire il file ($filename)";
exit;
}

// Scriviamo $somecontent nel nostro file aperto.
if (fwrite($fp, $somecontent) === FALSE) {
echo
"Impossibile scrivere nel file ($filename)";
exit;
}

echo
"Successo, scritto ($somecontent) nel file ($filename)";

fclose($fp);

} else {
echo
"Il file $filename non è scrivibile";
}
?>

Note

Nota:

Scrivere su uno stream di rete potrebbe terminare prima che l'intera stringa sia scritta. Il valore restituito da fwrite() potrebbe essere verificato:

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

Nota:

Su sistemi che differenziano tra file binari e di testo (ad esempio Windows), il file deve essere aperto con 'b' incluso nel parametro di modalità di fopen().

Nota:

Se stream è stato aperto in modalità append tramite fopen(), le scritture con fwrite() sono atomiche (a meno che la dimensione di data non superi la dimensione del blocco del filesystem, su alcune piattaforme, e purché il file sia su un filesystem locale). Cioè, non c'è bisogno di usare flock() prima di chiamare fwrite(); tutti i dati saranno scritti senza interruzione.

Nota:

Se si scrive due volte sul puntatore del file, i dati verranno aggiunti alla fine del contenuto del file:

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

// il contenuto di 'data.txt' è ora 123 e non 23!
?>

Vedere anche:

  • fread() - Legge un file salvaguardando la corrispondenza binaria
  • fopen() - Apre un file o un URL
  • fsockopen() - Apre una connessione a un socket appartenente a un dominio Internet o Unix
  • popen() - Apre un puntatore ad un file di processo
  • file_get_contents() - Legge un file all'interno di una stringa
  • pack() - Pack data into binary string

add a note

User Contributed Notes 10 notes

up
109
nate at frickenate dot com
14 years ago
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;
}
?>
up
3
divinity76 at gmail dot com
4 years ago
if you need a function that writes all data, maybe try

<?php

/**
* writes all data or throws
*
* @param mixed $handle
* @param string $data
* @throws \RuntimeException when fwrite returned <1 but still more data to write
* @return void
*/
/*private static*/
function fwrite_all($handle, string $data): void
{
$original_len = strlen($data);
if (
$original_len > 0) {
$len = $original_len;
$written_total = 0;
for (;;) {
$written_now = fwrite($handle, $data);
if (
$written_now === $len) {
return;
}
if (
$written_now < 1) {
throw new
\RuntimeException("could only write {$written_total}/{$original_len} bytes!");
}
$written_total += $written_now;
$data = substr($data, $written_now);
$len -= $written_now;
// assert($len > 0);
// assert($len === strlen($data));
}
}
}
up
3
niklesh at example dot com
4 years ago
$handles can also be used to output in console like below example

fwrite(STDOUT, "Console Output");
up
5
Chris Blown
21 years ago
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.
up
4
Anonymous
8 years ago
// 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

<?php

$gfz
= filesize_dir("d:\\starwars.mkv"); // 11,5GB
echo 'Z:',$gfz,PHP_EOL;

$fz = fopen('d:\\test2.mkv', 'wb');
$fp = fopen('d:\\starwars.mkv', 'rb');
echo
PHP_EOL;
$a = (float) 0;
while((
$l=fread($fp, 65536))) {
fwrite($fz, $l);
if((
$a+=65536)%5) echo "\r", '>', $a, ' : ' , $gfz;
}

fclose($fp);
fclose($fz);

// test2.mkv' is 11,5GB

function filesize_dir($file) {
exec('dir ' . $file, $inf);
$size_raw = $inf[6];
$size_exp = explode(" ",$size_raw);
$size_ext = $size_exp[19];
$size_int = (float) str_replace(chr(255), '', $size_ext);
return
$size_int;
}
?>
up
5
dharris dot nospam at removethispart dot drh dot net
17 years ago
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");
up
2
synnus at gmail dot com
8 years ago
// 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

<?php

$gfz
= filesize_dir("d:\\starwars.mkv"); // 11,5GB
echo 'Z:',$gfz,PHP_EOL;

$fz = fopen('d:\\test2.mkv', 'wb');
$fp = fopen('d:\\starwars.mkv', 'rb');
echo
PHP_EOL;
$a = (float) 0;
while((
$l=fread($fp, 65536))) {
fwrite($fz, $l);
if((
$a+=65536)%5) echo "\r", '>', $a, ' : ' , $gfz;
}

fclose($fp);
fclose($fz);

// test2.mkv' is 11,5GB

function filesize_dir($file) {
exec('dir ' . $file, $inf);
$size_raw = $inf[6];
$size_exp = explode(" ",$size_raw);
$size_ext = $size_exp[19];
$size_int = (float) str_replace(chr(255), '', $size_ext);
return
$size_int;
}
?>
up
4
php at biggerthanthebeatles dot com
21 years ago
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.
up
3
Anonymous
15 years ago
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.
up
2
chedong at hotmail dot com
21 years ago
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));
To Top