So the other day someone was looking for a quick php script that would load a random image from a folder (rotating banner script) and display it on their website. There are already a ton of scripts out there that do this but of course, this was an excuse to build something for fun. So, I decided to create a script that would do just this but with the least amount of code lines still keeping it efficient (again, just for fun). This is what I came up with:
<?php $files = @opendir($dir=trim($_REQUEST['dir'])) or die('Not Valid'); while($file = readdir($files)) preg_match('/(.png)|(.gif)|(.jpg)/i',$file) ? $images = array($file,substr($file,strlen($file)-3)) : null; count($images) ? header('Content-type: image/'.$images[$id=rand(0,count($images)-1)]) : die('Not Valid'); print file_get_contents($dir.(substr($dir,strlen($dir)-1)!='/'?'/':null).$images[$id]); ?>
So, in 4 lines I was able to accomplish the task. The way this code works, you pass the script a dir where you want the images to be loaded from. The page will then read the folder and create an array of all the pngs, gifs, and jpgs in that folder. Finally, it’ll randomly pick one, send the header for the proper file type, and spit out the image.
Here’s the example link (every time you reload this page you should see a different image):
The code for this to work in your page:
<img src="random_image.php?dir=/path/to/image/folder/" />
Pros: Flexible since you can just pass it any dir you want without having to change the code
Cons: You can pass it the dir you want so someone could easily try passing it different dirs for images you might not want people to see.
I have added some security to this. If a folder doesn’t exists or a folder that does exist but doesn’t have any images is passed, the page will return a ‘Not Valid’ message. Thoughts and/or comments are welcome. If you have an even better way of doing this do feel free to post. Hope this is useful.