I have a script that checks a zipfile containing a number of matching PDF+textfiles. I want to unpack, or somehow read the textfiles from the zipfile, and just pick out some information from the textfile to see that the file version is correct.
I was looking at the tempnam()
function to find an equivalent to make a tempdir, but maybe someone has a better solution for the problem.
The indexfile looks something like this. (->
is for TAB char).
I have made the function to extract the version from the textfile and to check if its correct already, its only the unpacking, tmpdir or some other solution im looking for.
1000->filename->file version->program version->customer no->company no->distribution
2000->pagenumber->more info->more info->...
So I first found a post by Ron Korving on PHP.net, which I then modified to make a bit safer (from endless loops, invalid characters, and unwritable parent dirs) and use a bit more entropy.
So, let's try it out:
Result:
quite easy (I took partly it from the PHP manual):
See: http://de.php.net/manual/en/function.tempnam.php
Please look at Will's solution below.
=> My answer should not be the accepted answer anymore.
The "mkdir" function raises a warning if the directory already exists, so you can catch this using "@mkdir" and avoid any race condition:
There are a lot of overkill answers to this question. One simple answer would be:
I wanted to add a refinement to @Mario Mueller's answer, as his is subject to possible race conditions, however I believe the following should not be:
This works because
mkdir
returnsfalse
if$tmp
already exists, causing the loop to repeat and try another name.Note also that I've added handling for
$mode
, with a default that ensures the directory is accessible to the current user only, asmkdir
's default is0777
otherwise.It is strongly advised that you use a shutdown function to ensure the directory is removed when no longer needed, even if your script exits by unexpected means*. To facilitate this, the full function that I use does this automatically unless the
$auto_delete
argument is set tofalse
.This means that by default any temporary directory created by
tempdir()
will have permissions of0700
and will be automatically deleted (along with its contents) when your script ends.NOTE: *This may not be the case if the script is killed, for this you might need to look into registering a signal handler as well.
Another option if running on linux with
mktemp
and access to theexec
function is the following:This avoids the potential (although unlikely) race issue above and has the same behavior as the
tempnam
function.