SPECIAL! Pre-Order my book Smashing Node.JS on Amazon today!
Show Posts
← Back to homepage

PHP provides two very useful functions to create temporary files. Instead of creating unnecessary tmp directories in your applications, it’s better to rely on the global directory assigned for that matter.

To create a unique file with the right permissions use the tempnam function:

$filename = tempnam('/tmp_directory', 'filePrefix');

You can test this from the command line like this:

php -R 'tempnam("/tmp", "hello");'

The output file looks something like this:

guillermo-rauchs-macbook-pro-15:tmp willy$ ls -la hello*
-rw-------  1 willy  staff  0 Mar 11 03:26 helloyvEzzb

Couple this function with sys_get_temp_dir and you’ve solved the dilemma:

$filename = tempnam(sys_get_temp_dir(), 'filePrefix');

2 Comments

tom said

this was a good tip!

Your thoughts?

About Guillermo Rauch:

CTO and co-founder of LearnBoost, developer, open source enthusiast, blogger.