PHP | tmpfile( ) Function

The tmpfile() function in PHP is an inbuilt function which is used to create a temporary file with a unique name in read-write (w+) mode.
The file created using tmpfile() function gets automatically deleted when close using fclose() or when there are no remaining references to the file handle.
The end of the script also results in the removal of the temporary file created using tmpfile() function.
The tmpfile() function takes no parameters and it returns a file handle which is similar to the one returned by fopen(), for the new file or FALSE on failure.

Syntax:

tmpfile()

Return Value:
It returns a file handle for the new file on success or FALSE on failure.



Errors And Exception:

  1. The temporary file is automatically removed when it is closed with fclose(), or when the script ends.
  2. The tmpfile() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False.

Examples:


Input :  $temp_pointer = tmpfile();
         fwrite($temp_pointer, 'temporary data');
         fclose(temp_pointer);
Output : 1

Input : $temp_pointer = tmpfile();
        fwrite($temp_pointer, "GeeksforGeeks");
        echo fread($temp_pointer, 2048);
        fclose($temp);

Output : Geeksforgeeks

Below programs illustrate the tmpfile() function.

Program 1

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to illustarte tmpfile( ) Function
  
$temp_pointer = tmpfile();
  
// Write on temporary file
fwrite($temp_pointer, 'temporary data');
  
// This removes the file
fclose(temp_pointer);
  
?>

chevron_right


Output:

1

Program 2

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to illustarte tmpfile( ) Function
  
$temp_pointer = tmpfile();
  
// Write on temporary file
fwrite($temp_pointer, "GeeksforGeeks");
  
// Read 2k from file
echo fread($temp_pointer, 2048);
  
// This removes the file
fclose($temp_pointer);
  
?>

chevron_right


Output:

GeeksforGeeks

Reference:
http://php.net/manual/en/function.tmpfile.php



My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.