3

I'm looking for a way to use the responsive image attribute 'srcset' alongside php. I'm currently using the following code in order to pick a random image from a directory on the server:

<?php
$dir = "img/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>

<img src="img/<?php echo $images[$i]; ?>" alt="image">

I've created different versions of the images in the directory with a suffix (i.e., image-1-small.jpg, image-1-big.jpg ... image-2-small.jpg, image-2-big.jpg etc.).

How would I implement the srcset attribute into the php string? I'm looking for an output similar to this:

<img sizes="100vw" srcset="img/image-1-small.jpg 400w, img/image-2-medium.jpg 800w, img/image-1-big.jpg 1600w" src="img/image-1-small.jpg" alt="image-1">

Thanks!

Dannie Vinther
  • 183
  • 1
  • 5

1 Answers1

1

You can try something like this:

<?php
$dir = "img/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
// Get image file name.
$image_name_full = $images[$i];
// Define display types.
$image_display_types = array("-small.jpg", "-medium.jpg", "-big.jpg");
// Remove image display type from image name.
$image_name = str_replace($image_display_types, "", $image_name_full);
?>

<img sizes="100vw" srcset="img/<?php echo $image_name; ?>-small.jpg 400w, img/<?php echo $image_name; ?>-medium.jpg 800w, img/<?php echo $image_name; ?>-big.jpg 1600w" src="img/<?php echo $image_name; ?>-small.jpg" alt="<?php echo $image_name; ?>">
stubben
  • 309
  • 2
  • 6
  • Thanks a lot! It almost worked perfectly. However, it didn't output the filename correctly (output -> `img/image-1.jpg-small.jpg`). So I had to remove the ".jpg" file extension as well. I don't know how to do it code efficiently so I just added this to the mix: `$image_display_formats = array(".jpg"); $image_n = str_replace($image_display_formats, "", $image_name_full);` Is there a more efficient way of doing it? – Dannie Vinther Dec 23 '15 at 10:42
  • I realized that I can do this: `$image_display_types = array("-small.jpg", "-medium.jpg", "-big.jpg");` – Dannie Vinther Dec 23 '15 at 11:35