Php write tmp file

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

Источник

PHP Create Temp File

Summary: in this tutorial, you will learn how to use the PHP tmpfile() and tempnam() functions to create a temporary file.

Introduction to the temp file

A temporary file only exists during the execution of the script. It means that PHP automatically deletes the temporary file when the script ends.

To create a temporary file, you use the tmpfile() function:

tmpfile ( ) : resource|falseCode language: JavaScript (javascript)

The tmpfile() function creates a temporary file in a read/write ( w+ ) mode. The tmpfile() function returns the filehandle. If the function fails to create the file, it returns false .

Note that the tmpfile() function creates a temporary file with a unique name.

In fact, PHP automatically deletes the temporary file created by the tmpfile() function:

  • When you close the file by calling the fclose() function.
  • When the file handle doesn’t have any references.
  • or when the script ends.

PHP tmpfile() function example

The following example uses the tmpfile() function to create a new temporary file and write a text to it:

 $f = tmpfile(); if (false !== $f) < // write some text to the file fputs($f, 'The current time is ' . strftime('%c')); > echo 'The current time is ' . strftime('%c'); exit(1); Code language: HTML, XML (xml)
  • First, create a new temporary file using the tmpfile() function.
  • Second, write a string to the file using the fputs() function.

The tempnam() function

The tempnam() function creates a temporary file in a directory and returns the full path to the temporary file:

tempnam ( string $directory , string $prefix ) : string|falseCode language: PHP (php)

The tempnam() function has two parameters.

  • $directory is the directory of the temporary file. If the directory doesn’t exist or isn’t writable, the tempnam() creates the temporary file in the system temporary directory specified by the TMPDIR environment variable on Unix or the TMP environment variable on Windows.
  • $prefix is the prefix of the temporary file name.

The following example shows how to use the tempnam() function to create a temporary file in the tmp directory:

 $name = tempnam('tmp', 'php'); // full path to the temp file echo $name; //C:\xampp\htdocs\tmp\phpA125.tmp // open the temporary file $f = fopen($name, 'w+'); if ($f) < // write a text to the file fputs($f, 'the current time is ' . strftime('%c')); fclose($f); >Code language: HTML, XML (xml)

In this example, if you pass an empty string to the directory, the tempnam() function will create the temporary file in the system temporary directory e.g., on Windows, it is: C:\Users\\AppData\Local\Temp\php778.tmp

Summary

  • Use the tmpfile() function to create a temporary file that exists only during the execution of the script.
  • Use the tmpname() function to create a temporary file in a directory and return the full path of the file.

Источник

PHP tmpfile() Function

Create a temporary file with a unique name in read-write (w+) mode:

fwrite($temp, «Testing, testing.»);
//Rewind to the start of file
rewind($temp);
//Read 1k from file
echo fread($temp,1024);

//This removes the file
fclose($temp);
?>

The output of the code above will be:

Definition and Usage

The tmpfile() function creates a temporary file with a unique name in read-write (w+) mode.

Note: The file is automatically removed when closed, with fclose() or when the script ends.

Tip: See also the tempnam() function.

Syntax

Technical Details

Return Value: A file handle (similar to the one returned by fopen() for the new file), FALSE on failure
PHP Version: 4.0+

❮ PHP Filesystem Reference

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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.

We can use the sys_get_temp_dir() function as the first parameter to the tempnam() function. The sys_get_temp_dir() function returns the default directory where PHP stores the temporary file.

As a result, a temporary file will be created in the default directory. We can get the temporary file path by displaying the tempnam() function with echo .

For example, create a variable $temp_path and assign it with the tempnam() function. Write the sys_get_temp_dir() function as the first parameter to the function and php as the prefix.

Next, use the echo function to print the $temp_path variable.

Consequently, the path of the temporary file is printed.

$temp_path = tempnam(sys_get_temp_dir(), 'php'); echo $temp_path; 

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

Related Article — PHP File

Источник

Читайте также:  Python method with return value
Оцените статью