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 ?
The file_exists() function checks whether a file or directory exists.
The file_exists() function in PHP is an inbuilt function which is used to check whether a file or directory exists or not. The path of the file or directory you want to check is passed as a parameter to the file_exists() function which returns True on success and False on failure.
PHP Create File - fopen() The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
exists(): Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise. Files.
You would have to do a glob():
$result = glob ("./uploads/filename.*");
and see whether $result
contains anything.
I've got the same need, and tried to use glob but this function seems to not be portable :
See notes from http://php.net/manual/en/function.glob.php :
Note: This function isn't available on some systems (e.g. old Sun OS).
Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.
It also more slower than opendir, take a look at : Which is faster: glob() or opendir()
So I've made a snippet function that does the same thing :
function resolve($name) { // reads informations over the path $info = pathinfo($name); if (!empty($info['extension'])) { // if the file already contains an extension returns it return $name; } $filename = $info['filename']; $len = strlen($filename); // open the folder $dh = opendir($info['dirname']); if (!$dh) { return false; } // scan each file in the folder while (($file = readdir($dh)) !== false) { if (strncmp($file, $filename, $len) === 0) { if (strlen($name) > $len) { // if name contains a directory part $name = substr($name, 0, strlen($name) - $len) . $file; } else { // if the name is at the path root $name = $file; } closedir($dh); return $name; } } // file not found closedir($dh); return false; }
Usage :
$file = resolve('/var/www/my-website/index'); echo $file; // will output /var/www/my-website/index.html (for example)
Hope that could helps someone, Ioan
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With