PHP: Create a Temporary File

So you need a temporary file to hold some middle data. There are 2 functions in PHP you can use for creating temporary files:

  1. PHP function tmpfile() creates a temporary file, opens it and returns the file handler:

    $temp_fh = tmpfile();
    f write($temp_fh, "The current time is ".strftime('%c'));
    // the file automatically goes away when the script ends

    Very handy for temporary uses.

  2. PHP function tempnam() is a little more sophisticated in that it takes 2 parameters to create a custom file and returns the path to the new file:

    $tempfilename = tempnam('/tmp', 'data-');
    $temp_fh = f open($tempfilename, 'w');
    f write($temp_fh, "The current time is ".strftime('%c'));
Scroll to Top