Displaying A Random Image From A Directory Via PHP
Recently asked on Yahoo! Answers:
In the past, I’ve been able to host a rotating image using another method by naming a folder ’something.png’ to fool a forum into thinking the folder is a picture and it reads the index.php file, which in turn pulls up one of the images I have coded. Now that I’m on Geocities Pro, I cannot make such a folder but would like to still use my rotating image. Is there another way I can code this and still be able to use it with forum BBCode?
Basically, this questioner wants a PHP script to look through the contents of an image directory, randomly select one of the images in that directory, and pass the script itself off as the image.
That’s fairly simple to do in PHP, but it does require a number of steps and a few tricks to overcome some limitations of PHP’s built-in filesystem functions.
This question also gives me a chance to explain working with the filesystem in PHP, and to demonstrate how loops and arrays can be used to produce some really neat results, so I’ll expand on that in a follow-up post.
As always, a working demo and source code will be available for download at the end of this article.
Continue reading ‘Displaying A Random Image From A Directory Via PHP’ »