views:

186

answers:

2

Hey All

I need to check if a file exists but I don't know the extension.

IE I would like to do:

if(file_exists('./uploads/filename')):
 // do something
endif;

Of course that wont work as it has no extension. the extension will be either jpg, jpeg, png, gif

Any ideas of a way of doing this without doing a loop ?

Thanks in advanced

+6  A: 

You would have to do a glob():

$result = glob ("./uploads/filename.*");

and see whether $result contains anything.

Pekka
`glob` can also be used with a bash-like brace expansion: `glob("./uploads/filename.{jpg,jpeg,png,gif}", GLOB_BRACE)`.
Gumbo
@Gumbo totally unrelated, may I ask where your avatar image comes from? I think I know that beaver from somewhere but can't place him.
Pekka
@Pekka: Ein kleiner Tipp: Blättere bei der nächsten Gelegenheit doch mal eine Ausgabe der Titanic durch.
Gumbo
@Gumbo das ist kein Problem, ich hab ein Abo :) Jetzt bin ich aber neugierig. *kram*
Pekka
@Gumbo ich komm nicht drauf! Aber vom Stil her würd ich sagen, Stephan Rürup?
Pekka
A: 

Did you know about the PHP filetype function? http://php.net/manual/en/function.filetype.php

Or otherwise is_file() http://www.php.net/manual/en/function.is-file.php

gearsdigital
This doesn't seem like it addresses the question at all
Michael Mrozek
But he can't get the filetype without knowing the complete filename, which is his exact problem. He knows the file is named 'filename.???', and needs to know how to find out the '???' without looping over a bunch of extensions checking each of them
Michael Mrozek
You are right... i missunderstood filetype. But he could do it with is_file(). Don't you think so?
gearsdigital
Well if the file or folder exists file_type will return it's type thus signaling that the file exists otherwise it returns false. I don't know what it considers an error though as it says it can return some warnings.
Gazillion
From the example:echo filetype('/etc/passwd'); // filemeaning you wouldn't need the extension, no?
Gazillion
@gears No, `is_file` also requires the complete filename
Michael Mrozek
@Gazillion `/etc/passwd` is a standard UNIX file that doesn't have an extension; that is the complete filename
Michael Mrozek
Ah okay, thanks for clarifying that for me :)
Gazillion