On the client side, there's no reason to make an AJAX call to figure out what image to show. Your <img>
tag can reference your PHP script directly:
<img src="getRandomImage.php" />
Normally, you're using PHP to return HTML, but there's no reason it can't return binary data as well. Here, we're just letting the browser do the work of making the request. Now, it's up to your server-side script to output the image.
In getRandomImage.php
, first you'll need to query for a random image. Best to let the database engine do this, as there's no sense in shuffling excess data between your application and your database server. Your query will look something like this:
SELECT blobData FROM images ORDER BY RAND() LIMIT 1;
(blobData
in this case is the name of the column containing the binary image data.)
Use your usual methods for making the query and getting the data. Now, to output it to something the browser can use, first we have to set the appropriate headers. The first sets the response content type to be JPEG. (Change it to whatever is appropriate for you image type, if you're not outputting JPEG.
header('Content-Type: image/jpeg');
Next, we need to prevent caching. This is important, as we're changing the response data for every request to this script:
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
Now, just output your image data.
echo $row['blobData'];
If all goes well, you should see the image in your image tag.
Improvements
Normally when you make a GET request, all subsequent GET requests to the same URL with the same request data should return the same response. While this isn't a technical requirement, it's a best practice that enables caches and what not to work correctly.
It is possible for you to still have cacheable images, while making the selection random. To do this, all you have to do is redirect to the image. For example, getRandomImage.php
might do something like this:
SELECT id FROM images ORDER BY RAND() LIMIT 1;
Then the response might just be a redirect:
header('Location: image.php?id=' . $row['id']);
Then in image.php
, you'll load the image by ID (not randomly) and output it, just as we did in the first example. Ideally, your images would just be static files and be accessible without this subsequent database lookup, and that random selection script could redirect to a static file directly. By default, PHP will do a 302 status code causing a non-permanent redirect which won't be cached in well-behaved clients.