• PHP Video Tutorials

PHP - Function fwrite()



The fwrite() function can write to an open file. The function can stop at the end of a file or when it can reach a specified length, whichever comes first. This function can return the number of bytes written or false on failure.

Syntax

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

This function can write the contents of string to file stream pointed to by handle.

Example-1

<?php
   $file = fopen("/PhpProject/sample.txt", "w");
   echo fwrite($file, "Hello Tutorialspoint!!!!!");
   fclose($file);
?>

Output

25

Example-2

<?php
   $filename = "/PhpProject/sample.txt";
   $somecontent = "Add this to the file\n";

   if(is_writable($filename)) {
      if(!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
       }
   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";
   }
?>

Output

Success, wrote (Add this to the file) to file (/PhpProject/sample.txt)
php_function_reference.htm
Advertisements