Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What is the fwrite() function in PHP?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

fwrite() is a built-in function in PHP.

The fwrite() function writes data to an open file. The data is passed a string.

The function will continue to write to the file until we either reach the end of the file, or attain the specified length, whichever comes first.

The fwrite function()

Syntax

The following is the function prototype:

fwrite(file, string, length)

Parameters and return value

The fwrite() function takes the following input parameters:

  • file: The file to which we write.

  • string: The data, as a string, to be written to the file.

  • length: An optional parameter that specifies the maximum number of bytes to be written.

The function returns the total number of bytes written in case of successful execution. Otherwise, the function returns FALSE.

Code

main.php
Edpresso.txt
<?php
$file = fopen("Edpresso.txt","r+");
echo fwrite($file,"Edpresso: Concise shots of dev knowledge!");
fclose($file);
echo "\n";
$file = fopen("Edpresso.txt","r+");
echo fgets($file);
fclose($file);
?>

In the example above, we open the Edpresso.txtfile. The data is written to the file using thefwrite()` function. The integer output represents the total number of bytes written to the file.

Next, to verify that the data has been successfully written to the file, we use fgets() to read data from the file.

RELATED TAGS

php

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring