PHP Basic Tutorial
MySQL Connection
PHP Advanced
In PHP, you can create and write to files using various functions like fopen()
, fwrite()
, and fclose()
.
The fopen()
function in PHP can be used to create a new file, Maybe a little confusing, but in PHP, a file is created using the same function used to open files.
The fopen()
create a new file if it doesn't exist, depending on the mode you choose. It is often used for file handling tasks like creating, reading, writing, or appending data.
The example below creates a new file called "testfile.txt". The file will be created in the same directory where the PHP code resides:
fopen()
fopen(filename, mode)
filename
→ The name of the file to be opened or created.mode
→ Specifies the mode for opening the file (e.g., read, write, append, etc.).If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.
The fwrite()
function is used to write data to a file in PHP. It works with fopen()
to create and modify files.
The first parameter of fwrite()
contains the name of the file to write to and the second parameter is the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
If we open the "newfile.txt" file it would look like this:
Overwriting a file in PHP means replacing its existing content with new data.All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into it:
If we now open the "newfile.txt" file, previous data have vanished, and only the data we just wrote is present:
Appending text means adding new content to an existing file without deleting its previous content.
In PHP, you can append text using fopen()
with "a"
mode. The "a" mode appends text to the end of the file, while the "w" mode overrides (and erases) the old content of the file.
In the example below we open our existing file "newfile.txt", and append some text to it:
If we now open the "newfile.txt" file, we will see that "This is a new line appended to the file." is appended to the end of the file: