PHP File Creation/Write
- Previous Page PHP File Open/Read
- Next Page PHP File Uploads
In this section, we will explain how to create and write files on the server.
PHP Create File - fopen()
The fopen() function is also used to create files. It may be a bit confusing, but in PHP, the function used to create files is the same as the function used to open files.
If you use fopen() to open a file that does not exist, this function will create the file, assuming the file is opened for writing (w) or appending (a).
The following example creates a new file named "testfile.txt". This file will be created in the same directory as the PHP code:
Example
$myfile = fopen("testfile.txt", "w")
PHP File Permissions
If an error occurs when you try to run this code, please check if you have PHP file access permission to write information to the hard disk.
PHP Writing File - fwrite()
The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the filename of the file to be written, and the second parameter is the string to be written.
The following example writes the name to a new file named "newfile.txt":
Example
<?php $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = "Bill Gates\n"; fwrite($myfile, $txt); $txt = "Steve Jobs\n"; fwrite($myfile, $txt); fclose($myfile); ?>
Please note that we wrote to the file "newfile.txt" twice. Each time we write to the file, in the string $txt we send, the first time it contains "Bill Gates", and the second time it contains "Steve Jobs". After writing is completed, we use the fclose() function to close the file.
If we open the "newfile.txt" file, it should look like this:
Bill Gates Steve Jobs
PHP Overwriting
If "newfile.txt" contains some data now, we can show what happens when writing to an existing file. All existing data will be erased and a new file will begin.
In the following example, we open an existing file "newfile.txt" and write some new data to it:
Example
<?php $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = "Mickey Mouse\n"; fwrite($myfile, $txt); $txt = "Minnie Mouse\n"; fwrite($myfile, $txt); fclose($myfile); ?>
If we open this "newfile.txt" file now, Bill and Steve have disappeared, and only the data we just wrote remains:
Mickey Mouse Minnie Mouse
PHP Filesystem Reference Manual
For a complete PHP Filesystem reference manual, please visit the one provided by CodeW3C.com PHP Filesystem Reference Manual.
- Previous Page PHP File Open/Read
- Next Page PHP File Uploads