tags:

views:

30

answers:

3

I've run into a typical problem here. Till now i was doing

strstr($filename,".");

$filename is the file i got from $_FILE i.e uploaded file.It was running fine until i hit a filename of the type i mentioned. Even doing

pathinfo($filename);

gives me

.gz 

I need to see whether it is EXACTLY

.tar.gz
+1  A: 

Technically, pathinfo is correct: the one and only extension for that file is .gz. The fact that it has .tar in the name is as coincidental as the fact that it has 5.0.1 in it.

That doesn't make your interest in checking for .tar.gz files invalid, but it does raise the question: what specifically do you want to find?

The most direct solution to your specific question is: first look for the extension (via pathinfo or the strpos function) and then if it happens to be .gz look for the "extension" in the remaining filename (via the same technique).

$parts = pathinfo($filename);
$extension = $parts['extension'];
if ($extension == '.gz') {
    $parts = pathinfo($parts['filename']);
    $extension = $parts['extension'] . $extension;
}
VoteyDisciple
i am ONLY looking for files with extension .tar.gz , i.e they should end with .tar.gz. So any file like this.is.a.long.filename.tar.gz should be valid..
uday
A: 

And if you needed to parse 'this.is.a.very.long.file.name.with.lots.of.full.stops' then what part of that is the file extension? Relying on a particular part of a filename to convey semantic, machine readable information about the contents of the file is, at best dangerous.

It's not clear what the problem you are trying is - why do you need to know what the extension is?

C.

symcbean
I have an upload form where i am restricting the user to upload ONLY .tar.gz archives. No other file type has to be allowed. So when he uploads something like mysql-5.0.1.tar.gz, my script says invalid file type because of the above logic. I need the extract the ".tar.gz" part from that file name. :)
uday
...so your solution is not fit for purpose - since the name of a file has nothing to do with its contents. If you want to validate the contents check that 'tar -tvzf $uploaded_file' returns no errors. And force a filename ending in .tar.gz or tgz on download.
symcbean
Yeah content validation is done later. If extraction fails i return an error.I am just checking if the file extension is .tar.gz. Basically saves a step. Shouldn't even bother extracting if its not .tar.gz. Not a very healthy way but it'll do .. So if the user deliberately names a file ending with tar.gz its gonna fail while extraction.
uday
Then check strripos($filename, '.tar.gz')==strlen('.tar.gz')
symcbean
+1  A: 

The most simple way would be to check for the last 7 characters of the filename - this ensures that every file ends with .tar.gz:

if (substr($filename, -7) == '.tar.gz') {
    // continue
}
Stefan Gehrig