Reading and Writing Temporary Files

While Cloud Storage is the recommended solution for reading and writing files in App Engine, if your app only needs to write temporary files, you can use standard PHP 7 methods to write files to a directory named /tmp.

All files in this directory are stored in the instance's RAM, therefore writing to /tmp takes up system memory. In addition, files in the /tmp directory are only available to the app instance that created the files. When the instance is deleted, the temporary files are deleted.

If you want to write a temporary file to permanent storage, create the file with App Engine's version of tempnam(). This version of tempnam() returns an in-memory temporary file that can be written to a permanent storage solution such as Cloud Storage buckets.

Here is an example on how to create an in-memory file with tempnam(), and then write to the file using file_put_contents() and fwrite():

$dir = sys_get_temp_dir();
$tmp = tempnam($dir, "foo");
file_put_contents($tmp, "hello");
$f = fopen($tmp, "a");
fwrite($f, " world");
echo file_get_contents($tmp);

This example will produce the following output:

hello world