PHP: Random Photo

Another snippet I’ve used (not any more) on WNLibrary:

/* NEW CODE ! */

/* extensions we check for */
$extensions = array('jpg','jpeg','gif','png','bmp');

/* folder to poll for content - do not forget trailing-slash at the end */
$ifp = '/home/neophyte/public_html/WNLibrary/Photographs/_cache/thumbs/';

/* the equivalent of $ifp except complete web-url */
$weburl = 'http://some.page.net/thumbs/';

/* SRC value */
$images = array();

srand((float) microtime() * 10000000); /* PHP < 4.2.0 */

/* open $ifp and poll it for content */
if ($handle = opendir($ifp)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." &amp;&amp; $file != "..") {

			/* extract file extension */
			$ext = strtolower(substr(strrchr($file, "."), 1));
                        /* check if we can use the extension */
			if(in_array($ext, $extensions))
			{
			$images[] = $weburl.$file;
			}

        }
    }
    closedir($handle);
}

if(!empty($images)) /* check if we have something to show */
{
$rand_key = array_rand($images, 1);

$src = $images[$rand_key];

echo "<img src='".$src."' alt='k0nslify' title='k0nslify'>";

unset($images[$rand_key]); /* we make sure the second image won't be the same as the first one */

$rand_key = array_rand($images, 1);

$src = $images[$rand_key];

echo "<img src='".$src."' alt='k0nslify' title='k0nslify'>";
}
else
{
echo 'No images were found in <strong>'.$ifp.'</strong>';
}

Leave a Reply

Your email address will not be published. Required fields are marked *