Call us Toll-Free:
1-800-218-1525
Live ChatEmail us

 Sponsors

Temporary File Names in C

Mike Peters, 05-27-2010
There's a lot of confusion among developers about the best way to generate a unique temporary file name in C.

If you're using C, the most suitable function that comes to mind is tmpnam():

char *tmpnam(char *str);

// Usage
printf ("My temporary file name is: %s\r\n", tmpnam("/usr/tmp"));

While it seems like a great fit, you should never ever use tmpnam.

I'll repeat it again - avoid using tmpnam() at all cost.

The reason is - tmpnam() suffers from a race condition:

Since the temporary file never gets created, if you have multiple threads/processes calling tmpnam() at the same time, it is very possible for two instances to end up with the same exact temporary file name... And the consequences can be fatal.

The tmpnam() function should be deprecated. That's probably why it was never ported over to PHP.

In PHP you should use tempnam() or tmpfile(), both of which create the temporary file before returning the name, so you are guaranteed no two instances will ever end up with the same temporary file name.

Here's the correct way to get a temporary file name in C:

char sTempfile[] = "/usr/tmp/mytmpfileXXXXXX"; // The X's are important
int tmp_handle;

if ( (tmp_handle=mkstemp(sTempfile)) < 1)
{
return 0;
}
close(tmp_handle);

// We now have the temporary filename in sTempfile
printf ("My temporary file name is: %s\r\n", sTempfile);

Mike Peters, 06-03-2010
One important thing to note when you're using tempnam() in PHP, followed by a move_uploaded_file.

move_uploaded_file is likely to change the file permissions, making the newly uploaded file not accessible to anyone.

To fix, so that you can have the security benefits of 755 while still allowing your php scripts to work, including the move_uploaded_file():

through shell access, navigate to the directory that contains your uploads folder and run the following 2 commands:

chown -R nobody uploaddir
chmod -R 755 uploaddir

Replace 'uploaddir' with the name of your uploads directory.

The first command changes the owner of the directory and files to 'nobody' which is what php operates under. The second changes the folder and files to only allow user access to writing. This is much more secure.
Enjoyed this post?

Subscribe Now to receive new posts via Email as soon as they come out.

 Comments
Post your comments












Note: No link spamming! If your message contains link/s, it will NOT be published on the site before manually approved by one of our moderators.



About Us  |  Contact us  |  Privacy Policy  |  Terms & Conditions