Here is a nifty PHP script I use on occasion. It reads a specified directory that you have populated with images, in this case .gif images then spits them out onto a nice 4 column table.
I used this for a page that displays customer logos. To add a new logo all the client has to do is size the image, make sure it’s a gif then drop it into the proper directory, done. To remove an image, just delete it from the directory. No code.
The client wanted to order 10 of the logos first and the rest alphabetically so I came up with the easiest solution I could think of witch was to put a sort on the array of file names before writing them to HTML then coming up with a file naming scheme that they could follow. I named the logos by the company name and just put a four digit number in front of the filenames they wanted to be ordered first. They started with 0010_name.gif then 0020_name.gif etc… This way if a new one came in that they wanted first they could name it 0015_name.gif.
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<?
$dir = 'path to directory';
$dirHandle = opendir($dir);
$image = "";
while ($file = readdir($dirHandle)) {
if(strpos($file, '.gif')>0) {
$count++;
$image[$count] = array ($file);
}
}
sort($image);
closedir($dirHandle);
$arrays = count($image) -1;
$loop = -1;
$c = 0;
while ($loop < $arrays) {
$loop++;
if ($c == 4) {
echo '</tr><tr><td><img src="the-directory/'.$image[$loop][0].'"></td>';
$c = 0;
} else {
echo '<td><img src="the-directory/'.$image[$loop][0].'"></td>';
}
$c++;
}
if ($c==1) {echo '<td colspan="3"></td>';}
if ($c==2) {echo '<td colspan="2"></td>';}
if ($c==3) {echo '<td></td>';}
if ($c==4) {echo '';}
?>
</tr>
</table>
July 9th, 2009 at 1:48 pm
Hi Norman,
Tried to use your code, but i’m getting these error lines:
Warning: sort() expects parameter 1 to be array, string given in /home/virtual/studiopa/public_html/preview/rooms_01.php on line 26
Fatal error: Cannot use string offset as an array in /home/virtual/studiopa/public_html/preview/rooms_01.php on line 37
What should i do?
July 9th, 2009 at 5:51 pm
There is no error trapping in this script so it could be several things.
Are there actually .gif files in the directory you are reading?
is $dir set to a relative path with a / at the end?
What version of php is running?
Try adding the following in under the $image=”";
if (!$dir) {echo ‘ERROR: No directory.’; exit;}
if (!$dirHandle) {echo ‘ERROR: Unable to open the directory.’; exit;}
Try replacing the sort($image); with this
if ($image == NULL) {
print(“Sorry, GIF files here”);
} else {
sort($image);
}