Amanda
Amanda

Reputation: 7

Set img src without knowing extension

So I have a few images in the server (public_html/img/profile_pictures/).

This is how I currently set the image:

echo "<img src='img/profile_pictures/main_photo.png'/>";

The main_photo can change each day, but if it changes to main_photo.jpg insted, it wont show (because the extension is hardcoded on that line(.png)). Is it possible to display the photo without knowing the extension for the image file?

Upvotes: 0

Views: 384

Answers (2)

clockw0rk
clockw0rk

Reputation: 568

if a Photo isn't loaded, it's width and size is null.

Although I would advise you to write a class that checks and loads images, I get a feeling you want a simple solution. so, given by the premise that the photo is either

<img src='img/profile_pictures/main_photo.png'/>

or

<img src='img/profile_pictures/main_photo.jpg'/>

and that neither this path nor this filename ever changes and in the folder is only one picture,

you could simply echo both.

The img of the one that is empty will not be shown. A better way was to write a class that loads your photo and checks if the photo is really there, like

$path = 'img/profile_pictures/main_photo.png';
if(!file_exists('img/profile_pictures/main_photo.png'))
{
     //use the jpg path
     $path = 'img/profile_pictures/main_photo.jpg';
}

You can ofc just inline this if case, but it's bad practise to intermix buisinesslogic and format logic, so I advice you to write a class for it.

Upvotes: 0

Chilarai
Chilarai

Reputation: 1888

If you want a PHP code, then try this. This code will look for main_photo.* inside your folder and automatically set the extension upon finding one.

Remember to set the path properly

<?php
$yourPhotoPath = "img/profile_pictures/";

foreach (glob($yourPhotoPath.'main_photo.*') as $filename) {

    $pathInfo = pathinfo($filename);
    $extension = $pathInfo['extension'];
    $fileName = chop($pathInfo['basename'], $extension);

    echo "<img src='".$yourPhotoPath.$fileName.$extension."'/>";
}
?>

Upvotes: 2

Related Questions