Technology: the only way to be a wizard if Hogwarts won't have you.

Yet another site hack: PHP random image generator.

Date/Time Permalink: 04/04/06 08:47:21 pm
Category: HOWTOs and Guides

Those of you who enter through my home page might now notice that it displays one random image from my graphics gallery on every visit/refresh. And heeeeere's how you do that!:

First off, you can't use PHP from a bare HTML page. You'll have to redirect your index.html -> index.php.

Next, the code: replace "./path/to/my/pictures/" with wherever your image folder is that you want to use.


<?php
   $PicFiles=array();
   $handle = opendir('./path/to/my/pictures/');
   $count=0;
   while (false !== ($file = readdir($handle))) 
   {
      if ((strpos($file, 'humb') ==
false)&&(strpos($file, 'ormal') ==
false)&&(strpos($file, 'jpg') == true))
      { 
        $PicFiles[$count]="./path/to/my/pictures/$file";
        $count++;
      }  
   }
   closedir($handle);
   $randpick=rand(0,$count);
   echo "<img src=$PicFiles[$randpick] height='150'
width='200' vspace='10' hspace='10'>";
 ?>

Stick it somewhere on your index.php. Note that here I have screened out strings for thumbnails and normals, and selected only jpg's. Alter that 'if' line to suit your needs! But why are they "humb" and "ormal"? Because PHP's strpos() returns zero in both cases where the string wasn't found, and in cases where it *was* found...at position zero!

This has been your hack 'o the day!

Follow me on Twitter for an update every time this blog gets a post.
Stumble it Reddit this share on Facebook

suddenly the moon