PHP Tutorial - PHP fwrite() Function






Definition

The fwrite() writes to an open file.

Syntax

PHP fwrite() Function has the following syntax.

fwrite(file,string,length)

Parameter

ParameterIs RequiredDescription
fileRequired.Open file to write to
stringRequired.String to write to the open file
lengthOptional.Maximum number of bytes to write

Return

This function returns the number of bytes written, or FALSE on failure.





Note

file_put_contents() and fwrite() complement functions file_get_contents() and fread(), respectively.

fwrite() works with the file handle returned by fopen().

fwrite() takes a string and an optional length to write as the third parameter.

If you do not specify the third parameter, all of the second parameter is written out to the file.

Example

Write to a file


<?PHP
      $filename = "test.txt";
      $handle = fopen($filename, "wb");
      $numbytes = fwrite($handle, "java2s.com");
      fclose($handle);
      print "$numbytes bytes written\n";

?>

The code above generates the following result.