Random Images From a Directory

By Korvin on Aug 13, 2009

Just change the directory to what you want, it's set to http://www.yoursite.com/images/ right now, so change to what you want.

Demo version: http://left4quake.com/test.php

$dir = "./images/";
$dh  = opendir($dir);
$a = array();
while ($filename = readdir($dh)) { $filename = $dir.$filename; if (getimagesize($filename)) { $a[]="$filename"; } }
$rand = array_rand($a, 1);
echo "<img src='$a[$rand]' style='max-width:100%;' />";

Comments

Sign in to comment.
raccoon   -  May 05, 2010

this seems like it'd be pretty resource intense if you had a large image directory.

what about getting a file count, then plucking the n'th random file?

 Respond  
Korvin   -  Aug 13, 2009

You cant easily make it into a random background by changing this:
echo "$a[$rand]";
to this:
echo "$a[$rand]";

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.