This tutorial will demonstrate how to write data to a file on the server in the PHP programming language. Code examples are provided to show you how it’s done.
Writing data to a file server-side is a common task. Whether you’re writing log files so you can debug your app, or saving user submitted data, you will need to save a file at some point in your web development career.
Writing data to a file in PHP is a three-step process. You must first open the file with the fopen() function, and then write to it with the fwrite() function, then close the file resource.
Creating or Opening a File with fopen()
The PHP fopen() function will open a file resource and provide a pointer to that resource which can be used by other functions. If a file does not exist at the path specified, a new file will be created.
fopen() expects both a file path and a mode as parameters – the mode specifies what type of access to the file is required – reading or writing, or both.
Writing/Saving to a File with fwrite()
The fwrite() function writes data to a file.
fwrite() expects two parameters – a file pointer supplied by fopen() and the data to be written.
fwrite() can be called multiple times while a file resource is open to write data to the file sequentially.
Closing a file with fclose()
The fclose() function closes a file pointer, freeing it for use by other processes.
You should always close file pointers when you aren’t using them to reduce the chance of conflicting with other processes which may be trying to read or write to the file.
Examples – Writing Data to Files in PHP
Show often works better than tell, so here is how fopen() and fwrite() are used in combination to write data to a file:
// Assign the file pointer from fopen to the variable $file // Note the write permission requested (w) $file = fopen("test.txt", "w") or die("Cannot open file."); // define the data to be written to the file $data = "Any text data will do.\n"; // Write the data to fhe file with fwrite() fwrite($file, $data); // Write some additional data to the file $data = "More text data to write.\n"; // Write the additional data to the file fwrite($file, $data); // Close the file fclose($file);
Watch Out! Data will be Overwritten!
Be aware that if the file already exists, it will be overwritten by any data called between fopen() and fclose().
Appending Data to a File in PHP
To append to the file instead of overwriting it, use the append (a) mode of fopen(), rather than the write (w) mode:
// Note the append permission requested (a) $file = fopen("test.txt", "a") or die("Cannot open file."); $data = "This will be appended to the end of an existing file.\n"; fwrite($file, $data); fclose($file);
A Note on Permissions
If you receive permission errors you will need to ensure the directory you are running the script from, or the current working directory, are writable by the PHP process. On web servers, this usually means the www-data user will require permission to wread and write.