Random image from directory. (perl)

Imagine you want to represent random image on the same URL. Easy thing!
First of all, place selected images in some directory, let's say "/my/images/".
Then put this script in your web directory and give him name "random.jpg":

#!/usr/bin/perl -w

use strict;
use warnings;
use CGI;

my $q = CGI->new();

my $dir = '/my/images/';
opendir DIR, $dir;
my @list= grep { ! /^\./ && -f $dir . $_ } readdir(DIR);
closedir DIR;

print $q->header({-type=>'image/jpg', -expires=>'+1s',
-Cache-Control=>"no-store, no-cache, must-revalidate" });
my $file = $dir . $list[int(rand($#list))];
open(IN,"<" . $file);
binmode(IN);
while(<IN>) { print $_; }
close IN;
Now add make it exacutable with chmod +x random.jpg command. and make some tweaking in .htaccess file, like this:
<FilesMatch "random\.jpg$">
    Options +ExecCGI
    SetHandler cgi-script
</FilesMatch>

Finally you can point you browser to your script, and try to reload image. Here is the result:
(try to reload page, image will be changed)

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.