I have a requirement to write a file as part of a PHP script (XML contents with a custom file extension), then once the file has been saved to then attach that to an email I'll be sending using PHP Mailer.
The emailing part is fine but I've never had to write a file with PHP before. The file is only required for the duration of the script and doesn't need to be kept permanently.
How can I write a file to a temporary location?
Do I need to clean up the temporary location when done with the file? If so, how?
The tmpfile function creates a temporary file and returns a file pointer. The mkstemp function creates a temporary file and returns a file descriptor. The mkdtemp function creates a temporary directory. The mktemp command is for creating a temporary file or directory from the shell.
Use mktemp -d . It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.
Temporary files, also called temp or tmp files, are created by Windows or programs on your computer to hold data while a permanent file is being written or updated. The data will be transferred to a permanent file when the task is complete, or when the program is closed.
For example, Microsoft Windows and Windows programs often create a file with a . tmp file extension as a temporary file. Programs like Microsoft Word may create a temporary hidden file beginning with a tilde and a dollar sign (e.g., ~$example. doc) in the same directory as the document.
To avoid the Write-Read-Delete cycle with an actual file on disk, I would keep all of your temporary "file" data stored in memory using php's built-in php://temp
and php://memory
IO stream wrappersdocs.
// open a temporary file handle in memory
$tmp_handle = fopen('php://temp', 'r+');
fwrite($tmp_handle, 'my awesome text to be emailed');
// do some more stuff, then when you want the contents of your "file"
rewind($tmp_handle);
$file_contents = stream_get_contents($tmp_handle);
// clean up your temporary storage handle
fclose($tmp_handle);
You never have to write or delete a file to the disk. Also, note the difference between using php://temp
and php://memory
from the docs on the topic:
php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With