🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

Make PHP Write to File: Use of Fopen and Fwrite Functions

Reading time 3 min
Published Aug 8, 2017
Updated Oct 2, 2019

This tutorial will explain how to create and open a file with fopen() function. You will also be introduced to PHP write to file method called fwrite().

The fopen() function is more flexible than readfile(): it is used not only for opening files but also for creating them. The process is similar to the situation with variables: when you try to open a file that does not exist, it is created for you.

The PHP fwrite method is used to write to an opened file. After that, you will be introduced to the number of bytes that were written successfully. If the PHP write to file process goes wrong, the function will return false.

PHP Write To File: Main Tips

  • PHP fopen() function is used to both open create and open a file, so most developers prefer it to readfile() due to more options.
  • PHP fwrite() function is used to write strings of data into a file.
  • If you run into troubles when trying to open files through PHP, check if the file access is granted to PHP.

Open and Create Files: fopen()

Look at the code example below. It shows how to use fopen() function to either make PHP create file or open an existing one. The result of the action depends on whether a file with such name is found. As we have mentioned before, if the file does not exist, the method will create it automatically:

Example
<?php
  $newfile = fopen('textfile.txt', 'w');
?>
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

fwrite() Method: Add Data

Now, this code example illustrates how to PHP write to file by using the fwrite() function. You will notice there are two parameters in the script. The first one specifies the files into which we insert new data, while the second represents the data we want to be written into them:

Example

<?php
 $newfile = fopen("textfile.txt", "w");
 $str = "random text";
 fwrite($newfile, $str);
 fclose($newfile);
?>

We can also use fright() to overwrite text that certain documents contain.

Look at the example below. By executing it, we would easily make PHP write to file called textfile.txt. The exact words to be written are shown to be random text:

Example
<?php
 $random_file = fopen("textfile.txt", "w");
 $str = "random text";
 fwrite($random_file, $str);
 fclose($random_file);
?>

In our next example, we open the existing file, delete all the existing data and start fresh with an empty file. Then, we use PHP fwrite() to write to textfile.txt file. Now, it will only contain specified words (new text):

Example
<?php
 $random_file = fopen("textfile.txt", "w");
 $str = "new text";
 fwrite($random_file, $str);
 fclose($random_file);
?>

Note: PHP file_put_contents() function can also be used to make PHP write to file.

More Code Examples

The script in the example below makes PHP create file called file.txt. If there is already an existing file with that particular name and there are any permission issues, the code will close and show an error Cannot open the file!

Example
<?php
 $new_file = fopen('file.txt', 'w') or die('Cannot open the file!');
 $text = 'random things';
 fwrite($new_file, $text);
 fclose($new_file);
?>

The code shown in the example below will create a completely empty file named empty.txt. If a file with such name already exists, all the information in it will be erased.

Example
<?php
 $new_file = fopen('empty.txt', 'w');
 fclose($new_file);
?>

PHP Write To File: Summary

  • PHP fopen() provides coders with more options than using only readfile() method: you can use it to open existing files and creating new ones as well.
  • To write data strings into files, use PHP file_put_contents() or fwrite() functions.
  • To be able to open files, PHP needs to be granted file access.