Php temporary files directory

sys_get_temp_dir

Returns the path of the directory PHP stores temporary files in by default.

Parameters

This function has no parameters.

Return Values

Returns the path of the temporary directory.

Examples

Example #1 sys_get_temp_dir() example

// Create a temporary file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam ( sys_get_temp_dir (), ‘Tux’ );

The above example will output something similar to:

See Also

User Contributed Notes 11 notes

If running on a Linux system where systemd has PrivateTmp=true (which is the default on CentOS 7 and perhaps other newer distros), this function will simply return «/tmp», not the true, much longer, somewhat dynamic path.

As of PHP 5.5.0, you can set the sys_temp_dir INI setting so that this function will return a useful value when the default temporary directory is not an option.

This function does not always add trailing slash. This behaviour is inconsistent across systems, so you have keep an eye on it.

It’s not documented but this function does not send the path with trailing spaces, actually it drops the slash if it exists.

it should be mentioned that the return value of sys_get_temp_dir() can be set using the ini-directive ‘sys_temp_dir’ globally as well as per directory by using
php_admin_value sys_temp_dir /path/to/tmp

A very helpful thing to note when on Linux:

If you are running PHP from the commandline you can use the environment variable: TMPDIR — to change the location without touching php.ini. — This should work on most versions of PHP.

Example file: test.php
echo sys_get_temp_dir () . PHP_EOL ;
?>

And then running:

TMPDIR=/custom/location php test.php
/custom/location

This function does not account for virtualhost-specific modifications to the temp path and/or open_basedir:


php_admin_value open_basedir /home/user
php_admin_value upload_tmp_dir /home/user/tmp
php_admin_value session.save_path /home/user/tmp

Within this config it still returns /tmp

That is important for the purposes of building paths through concatenation to know that sys_get_temp_dir does not include a path separator at the end.

So, sys_get_temp_dir() will return whatever your temp dir is set to, by default:

If you attempted to concatenate another dir name temp and use the following:

That would actually attempt to generate:
/tmpsome_dir

It would likely result in a permission error unless you are running a php script as a super user.

Instead you would want to do:
mkdir( sys_get_temp_dir() . DIRECTORY_SEPARATOR. ‘some_dir’ );

which would create:
/tmp/some_dir

I don’t know if Windows or other platforms include a directory separator at the end. So if you are writing something a bit more general you may want to check for the path separator at the end and if it is not there append it.

On windows, when PHP is used as CLI, this function will return the temp directory for the current user e.g. C:\Users\JohnSmith\AppData\Local\Temp\9 instead of C:\Windows\Temp.

Источник

tmpfile

Creates a temporary file with a unique name in read-write-binary (w+b) mode and returns a file handle.

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.

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 ( $temp , 0 );
echo fread ( $temp , 1024 );
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

User Contributed Notes 7 notes

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

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

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.

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);

register_shutdown_function(function() use($file) unlink($file);
>);

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)

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.

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.

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 );
>
>
?>

Источник

Create and Get the Path of tmpfile in PHP

Create and Get the Path of tmpfile in PHP

  1. Use the stream_get_meta_data() Function and uri Index to Create and Get the Path of tmpfile in PHP
  2. Use the tempnam() and sys_get_temp_dir() Functions to Create and Get the Path of tmpfile in PHP

This article will introduce methods to create temporary files and get their full path in PHP.

Use the stream_get_meta_data() Function and uri Index to Create and Get the Path of tmpfile in PHP

Temporary files are the files that hold the information temporarily while the program executes. Once the script or the program finishes its execution, the temporary file is deleted or transferred to a permanent file.

We can create temporary files in PHP with the tmpfile() function.

The temporary file created by the function has the read/write(w+) mode. It returns false in case of failure to make a temporary file.

We can use stream_get_meta_data() to get the path of the temporary file. The function takes a parameter that can be streams or file pointers.

It receives the header or metadata from the parameter and returns an array. We can use the file pointer of the temporary file created by the tmpfile() function and the uri index to return the temporary file path.

For example, create a temporay file with the tmpfile() function and store it in the $file variable. Next, use the stream_get_meta_data() function with $file as the parameter.

Assign it to the $temp_path variable. Finally, display the variable using the uri index.

As a result, we can see the temporary file’s location.

$file = tmpfile(); $temp_path = stream_get_meta_data($file); echo $temp_path['uri']; 

Use the tempnam() and sys_get_temp_dir() Functions to Create and Get the Path of tmpfile in PHP

We can also use the tempnam() function to create a temporary file in PHP. Using this function, we can give a unique name to the file.

The function takes two parameters. The first parameter specifies the directory where the temporary file is to be created, and the second is the filename prefix.

Источник

Читайте также:  Кроме последнего блока css
Оцените статью