Back to Top

How To Create a Temporary File in PHP

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.

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

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Most Popular Posts

Event Delegation in jQuery

Posted on 2 years ago

Bhumi

Learn ElasticSearch in 10 Minutes

Posted on 2 years ago

Bhumi

The Reader’s Poll – June 2015

Posted on 2 years ago

Bhumi

The Reader’s Poll – August 2014

Posted on 3 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 3 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 4 years ago

Bhumi

The Readers’ Poll – August 2013

Posted on 4 years ago

Bhumi