Hướng dẫn dùng tempfile temporarydirectory trong PHP

(PHP 4, PHP 5, PHP 7, PHP 8)

Show

tmpfileCreates a temporary file

Description

tmpfile(): resource|false

The file is automatically removed when closed (for example, by calling fclose(), or when there are no remaining references to the file handle returned by tmpfile()), or when the script ends.

Caution

If the script terminates unexpectedly, the temporary file may not be deleted.

Parameters

This function has no parameters.

Return Values

Returns a file handle, similar to the one returned by fopen(), for the new file or false on failure.

Examples

Example #1 tmpfile() example

$temp tmpfile();
fwrite($temp"writing to tempfile");
fseek($temp0);
echo 
fread($temp1024);
fclose($temp); // this removes the file
?>

The above example will output:

See Also

  • tempnam() - Create file with unique file name
  • sys_get_temp_dir() - Returns directory path used for temporary files

bishop

4 years ago

To get the underlying file path of a tmpfile file pointer:

$file = tmpfile();
$path = stream_get_meta_data($file)['uri']; // eg: /tmp/phpFx0513a

chris [at] pureformsolutions [dot] com

16 years ago

I found this function useful when uploading a file through FTP. One of the files I was uploading was input from a textarea on the previous page, so really there was no "file" to upload, this solved the problem nicely:

    # Upload setup.inc
   
$fSetup = tmpfile();
   
fwrite($fSetup,$setup);
   
fseek($fSetup,0);
    if (!
ftp_fput($ftp,"inc/setup.inc",$fSetup,FTP_ASCII)) {
        echo
"
Setup file NOT inserted

"
;
    }
   
fclose($fSetup);
?>

The $setup variable is the contents of the textarea.

And I'm not sure if you need the fseek($temp,0); in there either, just leave it unless you know it doesn't effect it.

Anonymous

5 years ago

Since this function may not be working in some environments, here is a simple workaround:

function temporaryFile($name, $content)
{
    $file = DIRECTORY_SEPARATOR .
            trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) .
            DIRECTORY_SEPARATOR .
            ltrim($name, DIRECTORY_SEPARATOR);

    file_put_contents($file, $content);

    register_shutdown_function(function() use($file) {
        unlink($file);
    });

    return $file;
}

divinity76 at gmail dot com

2 years ago

at least on Windows 10 with php 7.3.7, and Debian Linux with php 7.4.2,

the mode is not (as the documentation states) 'w+' , it is 'w+b'

(an important distinction when working on Windows systems)

elm at gmail dot nospamplease dot com

3 years ago

To get tmpfile contents:
  $tmpfile = tmpfile();
 
$tmpfile_path = stream_get_meta_data($tmpfile)['uri'];
 
// ... write to tmpfile ...
 
$tmpfile_content = file_get_contents($tmpfile_path);
?>

Perhaps not the best way for production code, but good enough for logging or a quick var_dump() debug run.

oremanj at gmail dot com

15 years ago

No, the fseek() is necessary - after writing to the file, the file pointer (I'll use "file pointer" to refer to the current position in the file, the thing you change with fseek()) is at the end of the file, and reading at the end of the file gives you EOF right away, which manifests itself as an empty upload.

Where you might be getting confused is in some systems' requirement that one seek or flush between reading and writing the same file.  fflush() satisfies that prerequisite, but it doesn't do anything about the file pointer, and in this case the file pointer needs moving.

-- Josh

ssandor

9 years ago

Beware that PHP's tmpfile is not an equivalent of unix' tmpfile.
PHP (at least v. 5.3.17/linux I'm using now) creates a file in /tmp with prefix "php", and deletes that file on fclose or script termination.
So, if you want to be sure that you don't leave garbage even in case of a fatal error, or killed process, you shouldn't rely on this function.
Use the classical method of deleting the file after creation:
$fn = tempnam ('/tmp', 'some-prefix-');
if (
$fn)
  {
   
$f = fopen ($fn, 'w+');
   
unlink ($fn);  // even if fopen failed, because tempnam created the file
   
if ($f)
      {
       
do_something_with_file_handle ($f);
      }
  }
?>