Temporary files

resource tmpfile ( void )

Very often you will find you want to work with a file as if it were a "scratchpad" - a holding area where you can write out temporary data for later use. To make this as easy as possible, PHP has a function called tmpfile() which takes no parameters, but will create a temporary file on the system, fopen() it for you, and send back the file handle as its return value.

That file is then yours to read from and write to all you wish, and is deleted as soon as you fclose() the file handle or the script ends. Here is an example of tmpfile() in use:

    $handle = tmpfile();
    $numbytes = fwrite($handle, $mystring);
    print "$numbytes bytes written\n";

As you can see, tmpfile() is a drop-in replacement for fopen()ing a known file, so it is easy to make use of.

If you want to know where these temp files are being saved, use the sys_get_temp_dir() function - it's new in PHP 5.2.1, but returns a string containing the directory used for creating temporary files.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Other file functions >>

Previous chapter: Deleting files with unlink()

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.