- tmpfile
- Parameters
- Return Values
- Examples
- See Also
- tmpfile
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 7 notes
- Saved searches
- Use saved searches to filter your results more quickly
- License
- mikehaertl/php-tmpfile
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- PHP tmpfile() Function
- Definition and Usage
- Syntax
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
tmpfile
Creates a temporary file with a unique name in read-write (w+) 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
PHP 8.2
(PHP 5 5.2.0, 7, 8) timezone_transitions_get Alias of DateTimeZone::getTransitions() This function an alias of: DateTimeZone::getTransitions()
(PHP 5 5.3.0, 7, 8) timezone_version_get Gets the of timezonedb Returns the current version of timezonedb.
(PHP 4 4.2.0, 5, 7, 8) token_get_all Split given source into PHP tokens token_get_all() parses the given code string into PHP language tokens using Zend
(PHP 4 4.2.0, 5, 7, 8) token_name Get the symbolic of given PHP token_name() gets the symbolic for PHP id value.
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
?>?php
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 );
>
>
?>
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A convenience class for temporary files
License
mikehaertl/php-tmpfile
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A convenience class for temporary files.
- Create temporary file with arbitrary content
- Delete file after use (can be disabled)
- Send file to client, either inline or with save dialog, optionally with custom HTTP headers
- Save file locally
use mikehaertl\tmp\File; $file = new File('some content', '.html'); // send to client for download $file->send('home.html'); // . with custom content type (autodetected otherwhise) $file->send('home.html', 'application/pdf'); // . for inline display (download dialog otherwhise) $file->send('home.html', 'application/pdf', true); // . with custom headers $file->send('home.html', 'application/pdf', true, [ 'X-Header' => 'Example', ]); // save to disk $file->saveAs('/dir/test.html'); // Access file name and directory echo $file->getFileName(); echo $file->getTempDir();
If you want to keep the temporary file, e.g. for debugging, you can set the $delete property to false:
use mikehaertl\tmp\File; $file = new File('some content', '.html'); $file->delete = false;
Default HTTP headers can also be added:
use mikehaertl\tmp\File; File::$defaultHeader['X-Header'] = 'My Default'; $file = new File('some content', '.html'); $file->send('home.html');
About
A convenience class for temporary files
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
COLOR PICKER
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.