How to Output Images using PHP?

Recently Jason posed a question in the PHP Forum which stated:

What I want to do is use a stylesheet to link to a php file.

background:url(#topofpage);

/images/layout/pic.php

What the pic.php has to do is identify all png/gif/jpg files in the layout directory, create an array of file names, then randomly output one of these images. I am pretty sure I can identify the files in the directory, create an array and randomly select one. It’s the final part which I don’t know how to do. How do I output the image?

Oh and can CSS actually do this?

The Answers

rewake commented,

You can’t do it with CSS. (well maybe with CSS3, but I wouldn’t recommend using it just yet).

Ok, CSS is out, let’s turn to PHP

Jason decided that he wanted to explore methods with PHP even though rich97 was able to explain a method in which php images can work inside css. So…

unitedcraig offered up the first tip:

If it is just a random image, then this is what you would need to do.

<img src=&quot;i/header_<?php echo(rand(1,4)); ?>.png&quot; alt=&quot;Header Image&quot; />

Make sure all your images have the same file extension, and name them all “header_1″,
“header_2″ etc. The PHP code then randomly selects a number from 1 to whatever,
giving you a random image on each refresh.

That certainly seems simple enough. But often in web development there can be more than one way to accomplish a particular task.

japh offered his opinion:

There are several ways to do this, so it’s really a matter of choosing the best way.
You could do it the way you were originally thinking, and PHP just returns an
appropriate image type’s header, and then reads in the image file as a string
and echoes it. That will work, I’ve done it before, just to see if it would!

However, I think the option unitedcraig mentions is a better one, though I’d do it with a

in the head of the page, rather than the src=”" of an .
It’s less intensive on the server, and achieves the same result!

Rakuli responded,

If you wanted to do everything server-side and read in a folder full of images
you could and surprisingly, the script is quite simple.

<?php
     // Initiate the images array.
    $images = array();

// Wrap it all in an exception so you can just dump a white background image if it all goes wrong

try {
    // Open the image directory
    $dir = dir('static');

    // Read through the diriectory
   while (false !== ($file = $dir->read())):

   // Check the file extension to see if it's a jp(e)g, png or gif
   if (preg_match('/.(jpeg|jpg|gif|png)$/i', $file)) {
       // If it is, add it to the images array
       $images[] = $file;
    }

   endwhile;

   // Now we have an array of the filenames inside of the chosen directory that are images
   // We need to select one and then output it to the buffer with the correct content-type

    // first check there are any images
    if (!count($images))
        throw new Exception('No images found in the directory');

    // get a random entry
    $image = array_rand($images);
    $image = $images[$image];

    // Now we'll get some info on this file, if it turns out it's not an image (due to MIME type), the exception will catch it
    if (!$details = getimagesize($dir->path . '/index.html' .  $image))
        throw new Exception('Could not get image details');

    // Now we have everything we need

   // Set the content type
   header ('Content-Type: ' . $details['mime']);

   // Dumpe the image

   echo  file_get_contents($dir->path . '/index.html' . $image);

   // Clean up
   $dir->close();

   exit();

} catch (Exception $e) {

     //If there was an error, we'll just create a new image on the fly and dump that to the screen

     $img = imagecreate(600, 600);

     // Black text to show the error
     $font = imagecolorallocate($img, 0, 0, 0);

    // Add the exception message to the string
    imagestring($img, 0, 0, 0, $e->getMessage(), $font);

    // now send to the browser

   header('Content-Type: IMAGE/PNG');
   imagepng($img);
   imagedestroy($img);
   exit();
}

?>

And you could consider rerouting through htaccess to make the extension
look prettier.

In Summary

Rakuli sums it up nicely by saying;

SO listing the benefits of each way:

Using PHP to read the file to the buffer, changing the content-type and sending
to the browser:

  • Files don’t have to be on the web root meaning the only way users can
    get to your images is through this php file — could be good for
    sensitive images. This is how Facebook serves its image galleries.
  • You can manipulate the images prior to sending out, could be good
    for fixed background sizes or adding text as I did in that blog post I
    mentioned.
  • You can have the file in the CSS file rather than inside the HTML.
  • It can be used from many pages at once.

For using strings as craig mentions:

  • It’s faster as you’re just pointing a HTTP request to have the server,
    not PHP, serve the image.
  • You can change it on a per page basis.
  • Makes the image easier to bookmark or view.

It’s a matter of what you want to do really.

To Be Continued…

More information has been posted within this thread and we invite you to read more and participate in this discussion by visiting this thread in our php forum.

Comments are closed.