Today I am going to explain one of the good and interesting features in PHP. If you want a file to hold some data temporarily, It’s possible with PHP and you can do it is with the tmpfile() function in PHP.
This function creates a temporary file with a unique random name in the current directory and opens this file for writing and it returns a file handle if succeed or returns false is if it is not able to create the file.The file is removed when fclose() is called with that file handle or file will be closed automatically when you close the file.
$fp = tmpfile(); //creates a randomly named temporary file fwrite($fp, 'store temporary data in a file'); fclose($fp); //To delete file
NOTE:The extension of created temporary file is .tmp
Now, If you want a temporary file to hold data to last the longer time, you can create a filename with tempnam( ) function.
NOTE:File created with the tempnam() function, file will not be removed automatically
$filename = tempnam('/tmp', 'cre'); $fp = fopen($filename, 'w'); fwrite($fp, 'store temporary data in a file'); fclose($fp); unlink($filename);
Here, tempnam( ) function takes two arguments.The first argument specifies the directory where the temporary file is created and the second argument is a prefix for the filename and it is not an optional so if you don’t want to pass prefix,just pass argument as blank quotes like tempnam(‘/tmp’, ”). If the directory doesn’t exist or if it isn’t writeable, tempnam( ) uses the system temporary directory(which is a default path) to create the temporary file.
To get the path where the temporary file is created, sys_get_temp_dir() function is used
Lets have a look into by example:
$temp_file = tempnam(sys_get_temp_dir(), ''); echo $temp_file;
sys_get_temp_dir() function returns the path where the temporary file is created.By default path of temporary file is C:WindowsTemp in windows.tmpfile() creates a randomly named temporary file.