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');
?>

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.
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()