Reputation: 87
I am trying to check whether a file name (user_id) with a particular extension exists in a location. Whenever I execute this only if part gets executed and the control does not goes to the else if part, even though the image is not of the png extension.
$img1 = "../img/profile_imgs/".$user_id.".jpg";
$img2 = "../img/profile_imgs/".$user_id.".png";
$img3 = "../img/profile_imgs/".$user_id.".jpeg";
if (is_bool(file_exists($img1))==1)
{
echo "am here in jpg";
$prof_img =$img_name_jpg;
}
else if (is_bool(file_exists($img2))==1)
{
echo "am here in png";
$prof_img =$img_name_png;
}
else if (is_bool(file_exists($img3))==1){
echo "am here in jpeg";
$prof_img =$img_name_jpeg;
}
Upvotes: 1
Views: 62
Reputation: 954
I think it will be better to keep file name in your database , and not try to guess the extension of the file. Anyways you can try the @Typoheads reply or function glob() if necessary http://php.net/manual/en/function.glob.php
Upvotes: 0
Reputation: 173542
In your code:
is_bool(file_exists($img1)) == 1
Tests whether the outcome of file_exists()
is a boolean, which it always is.
That said, you can write a small helper function that does the testing for you using an array of extensions you want to look for:
function filePathMatchingExtensions($path, array $extensions)
{
foreach ($extensions as $extension) {
if (file_exists($path . $extension)) {
return $path . $extension;
}
}
return false;
}
$extensions = ['.jpg', '.jpeg', '.png'];
$prof_img = filePathMatchingExtensions("../img/profile_imgs/$user_id", $extensions);
if ($prof_img !== false) {
// it exists
} else {
// it doesn't exist
}
Upvotes: 0
Reputation: 1878
Why do you use this complicated condition:
if (is_bool(file_exists($img1))==1)
This should work just fine:
$img1 = "../img/profile_imgs/".$user_id.".jpg";
$img2 = "../img/profile_imgs/".$user_id.".png";
$img3 = "../img/profile_imgs/".$user_id.".jpeg";
if (file_exists($img1))
{
echo "am here in jpg";
$prof_img = $img_name_jpg;
}
else if (file_exists($img2))
{
echo "am here in png";
$prof_img = $img_name_png;
}
else if (file_exists($img3))
{
echo "am here in jpeg";
$prof_img = $img_name_jpeg;
}
Upvotes: 1