Friday, November 21, 2025
HomeLanguagesHow to write Into a File in PHP ?

How to write Into a File in PHP ?

In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function.

The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file has to close by using the PHP fclose() function.

Syntax:

fwrite(file_name, string)
  • file_name: The name of the input file
  • string: The content to be written.

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

Example 1: The code example below shows how to write a text to the “neveropen_data.txt” file.

PHP




<?php
// Open a file named neveropen_data in write mode
$data = fopen("neveropen_data.txt", "w");
 
// writing content to a file using fwrite() function
echo fwrite($data, "This data is added as extra");
 
// closing the file
fclose($data);
?>


neveropen_data.txt: When the user opens this text file, the following text content is found after opening it.

This data is added as extra

Output:

27

Example 2:

PHP




<?php
// Open a file named neveropen_data in write mode
$data = fopen("neveropen_data.txt", "w");
 
// writing content to a file using fwrite() function
echo fwrite($data, "This data is added as extra
                    along with previous data");
 
// closing the file
fclose($data);
?>


neveropen_data.txt: The following content is found after opening the file.

This data is added as extra 
                   along with previous data

Output:

74
RELATED ARTICLES

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7166 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS