Make PHP Write to File: Use of Fopen and Fwrite Functions
In This Tutorial Developer Guidance (web developer blog) will guide and explain how to create and open a file with fopen() function.
fopen() function is a prdefined function of PHP, it is used for both Create and Open the file. If file does not exists then it will create the file.
PHP fwrite() function is used to write to an opened file. In other words
fwrite() function is used to write to a file. The first parameter contain file name to write and second parameter contain is a string to be written (w).
PHP Write To File:
- PHP fopen() function is used for create and open file.
- fwrite() PHP function is used to write string of data into the file.
- Directory must be writable by the web server user for the fopen() function to be able to create a file.
<?php $newfile = fopen('textfile.txt', 'w'); ?>
Above example show how to use fopen() function either create file or open the existing file.
fwrite() Method :
fwrite() function in php is used to write a file. fwrite() function is used to write content to a file when a file is already open in write mode.
<?php $newfile = fopen("textfile.txt", "w"); $str = "random text"; fwrite($newfile, $str); fclose($newfile); ?>
Append data to a File with PHP
You want to add more students name on student.txt then you need to open the file in append mode. For example
$file_name = 'student.txt'; //opens the file.txt file or implicitly creates the file $myfile = fopen($file_name, 'a') or die('Cannot open file: '.$file_name); $student_name = "John \n"; // write name to the file fwrite($myfile, $student_name); // lets write another movie name to our file $movie_name = "Tony \n"; fwrite($myfile, $student_name); // close the file fclose($myfile);
If student.txt file contain some data, we can show, what happen if we open the existing file for writing.All the date will be erased and we start with a empty file.
<?php $myfile = fopen("student.txt", "w") or die("Unable to open file!"); $txt = "John\n"; fwrite($myfile, $txt); $txt = "Doe\n"; fwrite($myfile, $txt); fclose($myfile); ?>