As we learned in the previous chapter that using fopen()
the function we can not only open but also create, write, overwrite and append files.
This task can be achieved using the second parameter of this function.
So when writing a file we would use “w” there instead of using “r” which is used in read operations.
Create File using fopen in PHP
The first thing you have to check before starting using the file creation function is that your PHP file where you are writing code has access to write files.
If it does not have access to writing files you will not able to write files using PHP.
That being said, if you want to write the file using fopnen()
function, here is how it can be done:
$myfile = fopen("myfile.txt", "w");
How to Write to file using fwrite function
In PHP fwrite()
function is used to write a file.
This function contains a two-parameter.
First, the parameter is the name of the file itself and the second is what we want to write in this file.
We also need to open the file in order to write something in it.
so for example here is how we can write the file using this function:
#Opening the file
$myfile = fopen("myfilename.txt", "w") or die("Unable to open file");
$txt = "This is my file";
# Writting on file
fwrite($myfile, $txt);
# Closing the file
fclose($myfile);
This code block would first open the file “myfilename.txt” if it does not exist it would create it.
After that using fwrite()
function, we successfully write $txt into that and closed the file.
How to Overwrite file in PHP
Overwriting files in PHP is simple as writing files for the first time.
When we overwrite a file, it would replace all of the previous content with the new one.
So we would use the same code but different file text for it:
#Opening the file
$myfile = fopen("myfilename.txt", "w") or die("Unable to open file");
$txt = "This is new text for the file";
# Writting on file
fwrite($myfile, $txt);
# Closing the file
fclose($myfile);
How to append text in already existed file?
We learned, how to write a file, how to overwrite it, and now we are going to see how to append content.
Appending means adding new content to an already written file but without removing it.
For appending instead of ‘r’ or ‘w’ we will use ‘a’ as the second parameter in fopen()
function.
Here is how it can be done:
#Opening the file
$myfile = fopen("myfilename.txt", "a") or die("Unable to open file");
$txt = "This is text that appendend in this file";
# Writting on file
fwrite($myfile, $txt);
# Closing the file
fclose($myfile);
So when you open and see the file, you would see that a new text is added just after the previously written texts.