The Wayback Machine - https://web.archive.org/web/20230422112939/https://www.geeksforgeeks.org/php-fwrite-function/
Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

PHP | fwrite( ) Function

Improve Article
Save Article
Like Article
author
Shubrodeep Banerjee
scholar
583 published articles
Improve Article
Save Article
Like Article

The fwrite() function in PHP is an inbuilt function which is used to write to an open file. The fwrite() function stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file, string and the length which has to be written are sent as parameters to the fwrite() function and it returns the number of bytes written on success, or FALSE on failure.

Syntax:

fwrite(file, string, length)

Parameters: The fwrite() function in PHP accepts three parameters.

  1. file : It is a mandatory parameter which specifies the file.
  2. string : It is a mandatory parameter which specifies the string to be written.
  3. length : It is an optional parameter which specifies the maximum number of bytes to be written.

Return Value: It returns the number of bytes written on success, or False on failure.

Exceptions:

  1. Both binary data, like images and character data, can be written with this function since fwrite() is binary-safe.
  2. If writing operation is performed twice to the file pointer, then the data will be appended to the end of the file content.

Examples:

Input : $myfile = fopen("gfg.txt", "w");
        echo fwrite($myfile, "Geeksforgeeks is a portal for geeks!");
        fclose($myfile);
Output : 36

Input : $myfile = fopen("gfg.txt", "w");
        echo fwrite($myfile, "PhP is Simple to Learn!");
        echo fwrite($myfile, "Geeksforgeeks is a portal for geeks!");
        fclose($myfile);
Output : 23
         59

Below programs illustrate the fwrite() function:

Program 1:




<?php
// Opening a file
$myfile = fopen("gfg.txt", "w");
  
// writing content to a file using fwrite()
echo fwrite($myfile, "Geeksforgeeks is a portal for geeks!");
  
// closing the file
fclose($myfile);
?>

Output:

36

Program 2:




<?php
// Opening a file
$myfile = fopen("gfg.txt", "w");
  
// writing content to a file using fwrite()
echo fwrite($myfile, "PhP is Simple to Learn!");
echo fwrite($myfile, "Geeksforgeeks is a portal for geeks!");
  
// closing the file
fclose($myfile);
?>

Output:

23
59

Reference : http://php.net/manual/en/function.fwrite.php


My Personal Notes arrow_drop_up
Last Updated : 19 Jun, 2018
Like Article
Save Article
Similar Reads
Related Tutorials