Jump to content

Need help with simple image gallery code


bluealien

Recommended Posts

Can someone help me clean this code up better, it works but I know it can be simpler?

 

Thanks for your help

 


<?php
// Images directories
$img_dir = 'images/';

// Validate its a JPE
if (preg_match("/\w+\.jpg$/",$_GET['p'])) { $image = $_GET['p']; }

// Read the directory and only get images
if ($handle = opendir($img_dir)) {
while (false !== ($filename = readdir($handle))) {
if (preg_match("/\w+\.jpg$/",$filename)) {
$files[] = $filename;
sort($files);
}
}
closedir($handle);
}

// If no image was set, we'll make the first image the default
if ($image && file_exists("$img_dir/$image")) {} else { $image = $files[0]; }

for ($i=0;$i<count($files);$i++) {
if ($files[$i] == $image) {
$last = $files[$i-1];
$next = $files[$i+1];
$image = $files[$i];
break;
}
}

?>
<center>
<?php echo "<img src='$img_dir/$image'>"; ?>
<p> </p>
<?php
if (file_exists("$img_dir/$last")) { echo "<a href='?p=$last'> « Last</a> | ";}
//
$imgdir = 'images/'; 
$allowed_types = array('png','jpg','gif'); 
$dimg = opendir($imgdir);  
while($imgfile = readdir($dimg))  
{ 
if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))  
{  
  $a_img[] = $imgfile;  
}   
} 
sort($a_img);  
$totimg = count($a_img); 
for($x=1; $x < $totimg;)  
{ 
echo "<a href='?p=$a_img[$x]'>$x</a> ";
$x++;  
}
//
if (file_exists("$img_dir/$next")) { echo " | <a href='?p=$next'> Next » </a>"; }
?> 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.