How do I write to a file using PHP?
This question is often asked in many ways, it could be how to add something to the end of a file, empty a file, or create a file. All of these operations come under writing to a file.
Firstly, there is a basic pattern to writing to a file, it goes something like this:
- Open the file using fopen
- Lock the file using flock
- Write to the file using fputs or fwrite
- Unlock the file using flock
- Close the file using fclose
This is the order that the operations (usually) need to be carried out in. The following example shows you how to create a file, then write a string to the file.
Handle - The name often given to the variable defined when using the fopen function.
Mode - A letter that represents how the file should be opened when using fopen.
$fp = fopen('filename.txt', 'w'); // set the handle to the variable $fp
// and open the file in "w" mode.
$string = 'Test String'; // set the $string variable
flock($fp, LOCK_EX); // lock the file "exclusivley" for writing
fputs($fp, $string); // write the data to the file
flock($fp, LOCK_UN); // unlock the file
fclose($fp); // always call fclose to close the file.
// forgetting to close or lock files is the main cause of
// files getting corrupted.
Now, to go over the example, the first line, where the fopen
function is used, opens the file in writeable mode... If the file does not exist it will attempt to create it. The important thing to remember about using the "w" mode in fopen
is that any data in the file will be truncated (emptied). There are other file handling modes, which can be looked up on the php website: <http://www.php.net/fopen
>. Some of these other modes will also be covered later in this post.
On the next line, we just simply set the variable $string to the value 'Test String'. This is the data that will get written into the file later on.
Next we lock the file using flock
. Using an exclusive lock, which is set by putting LOCK_EX, the file is locked from other scripts writing to the file or reading from it while we put the new information into the file. If the file isn't locked and two scripts try to write to it at the same time, it can get corrupted.
The next part is the part that actually writes the information to the file. Using the fputs
function it use the file path and data supplied ($fp and $string in this case), and writes $string to $fp.
From here, the file needs to be unlocked using flock
again, otherwise no other scripts would be able to write or read it. To unlock the file, we use LOCK_UN.
Finally, we have finished with the file so we can close it. Using the fclose
function we pass it the file handle ($fp) and it closes it. You should always do this as this is another thing that can lead to files getting corrupted.
If you try this and are still having problems, there are some possible reasons that it is failing, the most likley is that the file or directory you are trying to write to doesn't have the right permissions set. If you are on Linix machines (mosts PHP hosts will be running Linux), then you can CHMOD the file or directory to a value that will allow the scripts to be executed. For testing, I usually set it to 777. You can CHMOD from some FTP programs and online control panels. If you are not sure how to CHMOD on your hosting acount, you should contact your webspace provider.
This is the basics of writing to a file. Often, however, when you write to a file, you want to be able to add something on to the end of the file, and not delete everything that is in there first. This is very easy to alter, simply change the code:
This changes the file from opening to write mode (w) to ammend mode (a). When you write to the file now, anything you write to the file gets added onto the end after any existing data.
Finally, to bring this to a close, just a couple more points...
How to write to the beginning of a file?
- This only handles with writing to files, you can also read from filed but that is not discussed here
- There are many more modes for file handling, look at <http://www.php.net/fopen>
- There are also other types of file lock, and you can find these at <http://www.php.net/flock>
A common question is ,'how do you write to the beginning of a file' , the answer is not a new magic mode but a different approach , it should be noted that you can write to the beginning of a file by opening 'r+' and using fseek() to rewind to the start of a file then fputs() etc , however this will overwrite byte for byte the files existing contents.
To add a line to the beginning of a text file the most straightforward method is to read the file into memory , manipulate and then rewrite the file.
Newer PHP versions have handy functions such as file_get_contents
() to get the files data into a variable , you can also use the above noted functions to read a file into memory or the old sausage <?$str = implode( '', file( $filename ) ) ;?>
e.g. (no f
ing for clarity)
read the file contents into a variable
$filename = 'cars.txt' ;
$str = implode( '' , file( $filename ) ) ;
append your data
$str = "porche 911sc\n" . $str ;
open (overwrite) your existing file
$fp = fopen( $filename ,'w' ) ;
fputs( $fp , $str ) ;
fclose( $fp ) ;
Note that the above method becomes resource intensive with larger files.