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.
tmpfile() function
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.
1 2 3 4 5 | $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
tempnam() function
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
1 2 3 4 5 6 7 | $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:
1 2 3 4 | $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.
Further Reading:
To get all child categories in PHP
To extract RSS XML feed in PHP
Increase Max Upload File Size in PHP
gethostbyaddr function in PHP
I hope you have enjoyed this article. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.
Comments (1)