How to find different types of file from a path

91 views Asked by At

A user avatar is saved in ../wordpress/wp-content/uploads/ folder with name and extension as that of input. That is, If a PNG file is uploaded, the extension becomes user_avatar0.png, otherwise if JPG is uploaded it will becomes user_avatar0.jpg. I am loading multiple user avatars using for each loop.

This is the code I have used to load avatar file :

$path="../wordpress/wp-content/uploads/";
$av=$path."user_avatar0.png|.jpg"; // if jpg exists loads jpg otherwise load png
<img src="'. $av .'"   height="200" width="200" border="0" >

How to select a file from a directory, that contains files of different extensions(jpg, png etc.) ?

1

There are 1 answers

3
Markus AO On

What you have attempted with the clever .png|.jpg is unfortunately not a known syntax. It won't be interpreted by either PHP or the browser that parses the HTML. PHP doesn't have a feature that'd auto-fill path variables in way of shell parameter expansion ? . There's of course glob(), but globbing the whole directory to get a single file with either jpg/png extension would be very inefficient.

If you have no record of what the file extension is (you could query your WP database?), you'll have to simply check with something like this, presuming jpg/png are the only possibilities:

$file = 'user_avatar0.';
$file .= file_exists($file.'jpg') ? 'jpg' : 'png';

This concatenates the basename with a jpg extension if there's a match, and falls back to png if not. If there's a chance the user has no avatar at all, then you should do if-elseif-else instead, and default to a standard placeholder if both file_exists checks fail. You could also use realpath(), is_file() or stream_resolve_include_path() to verify if a file exists; but the logic remains the same. Rumor goes the last option would be the fastest, but in any case each of them caches its results.

Regardless, if you keep displaying the same users' avatars on recurring page-loads, you'll want to consider saving the results of these checks into a $_SESSION array to eliminate repeated and redundant checking. I'll leave it to you to benchmark PHP's filesys cache vs. session cache.