Hello all, first time working with PHP, had a question. Working on a friend's website, we thought we'd be wicked cool and add a dynamic photo gallery. I stunbles across this neat pile of code:

<?php

$columns     = 2;
$thmb_width  = 120;
$thmb_height = 80;

function resizeImage($originalImage,$toWidth,$toHeight){
    
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;
    
    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }
    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 
                       $new_width, $new_height, $width, $height);

    return $imageResized;
} 

function generateThumbnails(){
    global $thmb_width,$thmb_height;
    
    // Open the actual directory
    if ($handle = opendir(".")) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                      $isThumb = true;
                  } else {
                      $isThumb = false;
                  }
              
                  if (!$isThumb) {
                      // Process the file string
                      $dirName  = substr($file,0,strpos($file,basename($file)));
                      if (strlen($dirName) < 1) $dirName = '.';
                      $fileName = basename($file);
                      $fileMain = substr($fileName,0,strrpos($fileName,'.'));
                      $extName  = substr($fileName,strrpos($fileName,'.'),
                                          strlen($fileName)-strrpos($fileName,'.'));
                      
                      // Check if the actual file is a jpeg image
                      if (($extName == '.jpg') || ($extName == '.jpeg')){
                        $thmbFile = $dirName.'/'.$fileMain.'_th.jpg';
                        // If a thumbnail dosn't exists tahn create a new one
                        if (!file_exists($thmbFile)){
                            imagejpeg(resizeImage($file,$thmb_width,$thmb_height)
                                     ,$thmbFile,80);
                        }
                    }
                  } 
               }
           }
    }
    
}

function getNormalImage($file){
    $base = substr($file,0,strrpos($file,'_th.jpg'));
    if (file_exists($base.'.jpg')) return $base.'.jpg';
    elseif (file_exists($base.'.jpeg')) return $base.'.jpeg';
    else return "";
}

function displayPhotos(){
    global $columns;
    
    generateThumbnails();
    $act = 0;
    // Open the actual directory
    if ($handle = opendir(".")) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                    ++$act;
                    if ($act > $columns) {
                        echo '</tr><tr>
                           <td class="photo"><a href="'.getNormalImage($file).'">
                               <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                        $act = 1;
                    } else {
                        echo '<td class="photo"><a href="'.getNormalImage($file).'">
                           <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                    }
                      
                  }
              }
        }
    }    
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "DTD/xhtml1-transitional.dtd">
<html>
<head>
   <title>Photo Gallery</title>
</head>
<body>
  <center><h3>Photo Gallery</h3></center>
  <table align="center"><tr>     
    <?php displayPhotos(); ?>
  </table>        
</body>   


</html>

It works great! Just two things. I am having trouble re-defining where the images are read from. Right now it is the root, but, we want a folder called images to store content. And, we want it to read tif, and gif images. Right now it only reads jpg. I tried copy and pasting the sections that referenced file types and replacing gif as extension, would just throw up errors. I am not very experienced with the language. Any help, very appreciated. Cheers!

Recommended Answers

All 12 Replies

The lines you want to change are opendir(".") , this tells it to look in the current directory (where the script is located) May be worth adding a variable for directory at the top with the attributes and replacing the "." with it, there are 2 instances of opendir, so replace "." with $directory or whatever you call the variable.

Well, I changed my code thusly:

<?php

$columns     = 2;
$thmb_width  = 120;
$thmb_height = 80;
$directory   = "G:/xampp/xampp/htdocs/";

function resizeImage($originalImage,$toWidth,$toHeight){
    
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;
    
    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }
    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 
                       $new_width, $new_height, $width, $height);

    return $imageResized;
} 

function generateThumbnails(){
    global $thmb_width,$thmb_height;
    
    // Open the actual directory
    if ($handle = opendir($directory)) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                      $isThumb = true;
                  } else {
                      $isThumb = false;
                  }
              
                  if (!$isThumb) {
                      // Process the file string
                      $dirName  = substr($file,0,strpos($file,basename($file)));
                      if (strlen($dirName) < 1) $dirName = '.';
                      $fileName = basename($file);
                      $fileMain = substr($fileName,0,strrpos($fileName,'.'));
                      $extName  = substr($fileName,strrpos($fileName,'.'),
                                          strlen($fileName)-strrpos($fileName,'.'));
                      
                      // Check if the actual file is a jpeg image
                      if (($extName == '.jpg') || ($extName == '.jpeg')){
                        $thmbFile = $dirName.'/'.$fileMain.'_th.jpg';
                        // If a thumbnail dosn't exists tahn create a new one
                        if (!file_exists($thmbFile)){
                            imagejpeg(resizeImage($file,$thmb_width,$thmb_height)
                                     ,$thmbFile,80);
                        }
                    }
                  } 
               }
           }
    }
    
}

function getNormalImage($file){
    $base = substr($file,0,strrpos($file,'_th.jpg'));
    if (file_exists($base.'.jpg')) return $base.'.jpg';
    elseif (file_exists($base.'.jpeg')) return $base.'.jpeg';
    else return "";
}

function displayPhotos(){
    global $columns;
    
    generateThumbnails();
    $act = 0;
    // Open the actual directory
    if ($handle = opendir($directory)) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                    ++$act;
                    if ($act > $columns) {
                        echo '</tr><tr>
                           <td class="photo"><a href="'.getNormalImage($file).'">
                               <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                        $act = 1;
                    } else {
                        echo '<td class="photo"><a href="'.getNormalImage($file).'">
                           <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                    }
                      
                  }
              }
        }
    }    
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "DTD/xhtml1-transitional.dtd">
<html>
<head>
   <title>Photo Gallery</title>
</head>
<body>
  <center><h3>Photo Gallery</h3></center>
  <table align="center"><tr>     
    <?php displayPhotos(); ?>
  </table>        
</body>   


</html>

...and now nothing shows up. I have tried pointing it to different folders, all with the same result. They all contain jpgs, not sure why it doesn't work. And if anyone knows how to add file extensions, or would just recommend to convert them all to jpegs, I would appreciate it. Cheers.

what are the file extensions? jpg, jpeg, JPG or JPEG?

Have you had a look at the source code of the HTML produced to see what it is actually outputting?

Well, the files are all JPEG extensions. When leaving the location as ".", all the JPEG and JPG files show up on the page. When using the $dir, I get a page with just the Photo Gallery title, no pictures, even though it is pointing to the same exact place. View page source, just shows the html at the bottom of the above code, without the php call to the displayPhotos() function. I believe that is what you are asking. I know in Python there is the stdin/stdout to read what the input/output, I don't know if php has a similar function, and that is what you are referring to.

Had another look, you should define $directory as a global in the functions, just as the $thmb and $columns variables are.
Also, use a relative directory, change $directory = "G:/xampp/xampp/htdocs/"; to $directory = "."; and see if you get the correct output.

I'm coming in to the middle part of this
but whenever I have something that works with a fixed value, that doesnt work with a variable, I left the quotes out
Debugging is fastest if you use the same value of the variable as the original fixed value
index.php?directory=.

check the exact format of the variable
if the original is readdir("."); the replacement variable should be readdir("$directory"); the quotes are still required and dquotes should parse properly

Thanks both of you, first off. Now I have added the $dir variable as a global, and when designating the path as ".", I get the thumbs to display. When I change it to G:\xampp\xampp\htdocs\images, I get:
Warning: opendir(G: mpp mpp\htdocs\images) failed to open
The issue here looks like an escape character issue, yet only applied to the fist two directories. In python, \ is the escape character (ie: G:\\xampp\\xampp\\htdocs\\images), so I'm not sure the issue here. Thanks again.

Thanks both of you, first off. Now I have added the $dir variable as a global, and when designating the path as ".", I get the thumbs to display. When I change it to G:\xampp\xampp\htdocs\images, I get:
Warning: opendir(G: mpp mpp\htdocs\images) failed to open
The issue here looks like an escape character issue, yet only applied to the fist two directories. In python, \ is the escape character (ie: G:\\xampp\\xampp\\htdocs\\images), so I'm not sure the issue here. Thanks again.

Firstly, should the slashes not be forward slashes, rather than back slashes?
"G:/xampp/xampp/htdocs/images/"
I'm fairly sure it's only windows that does it this way - "\".
Secondly, have you tried a relative path instead of an absolute one?
ie. If your script is in "htdocs", instead of giving the address as "G:/xampp/xampp/htdocs/images/" all it would need to be is "images/"
Just some thoughts...

index.php?directory=G:\xampp\xampp\htdocs\images
I get errors if the directory is not quoted

opendir(G:\xampp\xampp\htdocs\images)
opendir(".")// note the quotes in the original
opendir("G:\xampp\xampp\htdocs\images")

quotes are still important
the variable gets

opendir("$directory") // Note the quotes

and works

every function("string") has to enclose the string in quotes,
include("filename")
fopen("filename")
fclose("filename")

Sorry i haven't responded, was away for the weekend. I have moved this to a Ubuntu testing server. I made a few changes. I installed imagemagick and ghostscript to convert all the images to jpgs, I am using the exec command to run them, and wildcards to define them. I have a feeling this will blow up in my face. In testing the convert string, i ran "convert filename.bmp *.jpg". When doing this, the file was converted, but it renamed it with a random(seemingly) name of a different jpg. Instead of "filename.jpg", it was "existingjpg.jpg.0" adding a number to the end to differentiate from the original. Also getting this message:
Warning: chdir() [function.chdir]: No such file or directory (errno 2) in /var/www/dbc/tstgygal2.php on line 8.
Poked around online alittle, and most common response was that it was an issue with not being a valid directory. I can cd into and run a list, it exists. Here is the current code.

<?php

$columns     = 4;
$thmb_width  = 120;
$thmb_height = 80;
$dir = "/dbc/trade_docs/";

echo chdir('$dir');

echo exec('convert *.pdf *.jpg');
echo exec('convert *.gif *.jpg');
echo exec('convert *.bmp *.jpg');
echo exec('convert *.tif *.jpg');

function resizeImage($originalImage,$toWidth,$toHeight){
    
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;
    
    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }
    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 
                       $new_width, $new_height, $width, $height);

    return $imageResized;
} 

function generateThumbnails(){
    global $thmb_width,$thmb_height,$dir;
    
    // Open the actual directory
    if ($handle = opendir("$dir")) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                      $isThumb = true;
                  } else {
                      $isThumb = false;
                  }
              
                  if (!$isThumb) {
                      // Process the file string
                      $dirName  = substr($file,0,strpos($file,basename($file)));
                      if (strlen($dirName) < 1) $dirName = '.';
                      $fileName = basename($file);
                      $fileMain = substr($fileName,0,strrpos($fileName,'.'));
                      $extName  = substr($fileName,strrpos($fileName,'.'),
                                          strlen($fileName)-strrpos($fileName,'.'));
                      
                      // Check if the actual file is a jpeg image
                      if (($extName == '.jpg') || ($extName == '.jpeg')){
                        $thmbFile = $dirName.'/'.$fileMain.'_th.jpg';
                        // If a thumbnail dosn't exists tahn create a new one
                        if (!file_exists($thmbFile)){
                            imagejpeg(resizeImage($file,$thmb_width,$thmb_height)
                                     ,$thmbFile,80);
                        }
                    }
                  } 
               }
           }
    }
    
}

function getNormalImage($file){
    $base = substr($file,0,strrpos($file,'_th.gif'));
    if (file_exists($base.'.gif')) return $base.'.gif';
    elseif (file_exists($base.'.gif')) return $base.'.gif';
    $base = substr($file,0,strrpos($file,'_th.jpg'));
    if (file_exists($base.'.jpg')) return $base.'.jpg';
    elseif (file_exists($base.'.jpeg')) return $base.'.jpeg';
    else return "";
}

function displayPhotos(){
    global $columns,$dir;
    
    generateThumbnails();
    $act = 0;
    // Open the actual directory
    if ($handle = opendir("$dir")) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                    ++$act;
                    if ($act > $columns) {
                        echo '</tr><tr>
                           <td class="photo"><a href="'.getNormalImage($file).'">
                               <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                        $act = 1;
                    } else {
                        echo '<td class="photo"><a href="'.getNormalImage($file).'">
                           <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
                    }
                      
                  }
              }
        }
    }    
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "DTD/xhtml1-transitional.dtd">
<html>
<head>
   <title>Photo Gallery</title>
</head>
<body>
  <center><h3>Photo Gallery</h3></center>
  <table align="center"><tr>     
    <?php displayPhotos(); ?>
  </table>        
</body>   


</html>

Any help, once again, greatly appreciated.

You can pretty much disregard that last post, I am going to deal with the image conversion in a different manner. Really, all I want is to ready the JPGS from the directory. I added an echo after the readdir, and it listed all the files in that directory, except, none of them show up on the page, the only time it shows up is when the directory is set to ".". I even have the script rendering in a frame on another page, so close, yet I cannot get this to work. Any help?

OP again, I have added the $dir in the globals for each function, and still, I do not get anything to appear in the frame. When I rem out the $dir global and just point to the root, I get images. They are all lower case jpg extension, so I know that is not at issue. Here is the code once again, I really can't get why I cannot read from a different directory besides the root.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Welcome to Dirty Blonde Cocktails</title>
<style type="text/css">
<!--
body { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; line-height:15px; color:#666; }
h1 { font-family:Helvetica, Arial, sans-serif; font-weight:normal; font-size:8px; line-height:24px; letter-spacing:-1px; color:#999; margin:0; padding:0; }
h2 { font-family:Helvetica, Arial, sans-serif; font-weight:normal; font-size:8px; color:#333; }<br />
h3 { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:6px; line-height:12px; color:#666; }

ul { padding:0; margin:0 0 0 5px; }
	li { list-style:none; padding:0; margin:0 0 8px 0; color:#333; }

#container {  }width:545px;

.box { margin:0 0 50px 0; }

.flavors ul { list-style:none; padding:0; margin:0; }
	.flavors li { list-style:none; display:inline; padding:5px; margin:0 0 5px 0; font-weight:bold; font-size:12px; }
		.rasp { color:#DF047A; }
		.peach { color:#F39A65; }
		.gf { color:#F7AE2F; }
		.lime { color:#6CB938; }

.desc { border:4px solid #ddd; background:#efefef; margin:10px; padding:10px; }

.howCopy { width:310px; float:left; }
.howPic { width:200px; float:right; border:1px solid #ddd; padding:5px; font-size:10px; text-align:center; color:#DF047A; }

.clear { clear:both; }

*					{ margin: 0; padding: 0; }
a img, img 			{ border: none; }

#page-wrap			{ width: 540px; margin: 0 auto; }

.photo-link			{
	font-family:Verdana, Arial, Helvetica, sans-serif;
	font-size:12px;
	line-height:15px;
	color:#666;
	padding: 5px;
	margin: 5px;
	border: 1px solid #999;
	display: block;
	width: 150px;
	height: 150px; /*added this line to sqaure up the box for proper formatting need the same HxW*/
	valign: center;
}
.photo-link:hover	{ border-color: white; }

-->

</style></head>

<body>

<!-- Add align center to the Div container (outer box) to center the inner table -->

<div id="container" align="center"><br />

<table align="center" border="0" cellspacing="5" cellpadding="0">
<?php

#$dir = "gallery/";
$columns = 2;
$thmb_width  = 150;
$thmb_height = 150;

function resizeImage($originalImage,$toWidth,$toHeight){

    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;

    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }
    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0,
                       $new_width, $new_height, $width, $height);

    return $imageResized;
}

function generateThumbnails(){
    global $thmb_width,$thmb_height,$dir;

    // Open the actual directory
    if ($handle = opendir("$dir")) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                      $isThumb = true;
                  } else {
                      $isThumb = false;
                  }

                  if (!$isThumb) {
                      // Process the file string
                      $dirName  = substr($file,0,strpos($file,basename($file)));
                      if (strlen($dirName) < 1) $dirName = '.';
                      $fileName = basename($file);
                      $fileMain = substr($fileName,0,strrpos($fileName,'.'));
                      $extName  = substr($fileName,strrpos($fileName,'.'),
                                          strlen($fileName)-strrpos($fileName,'.'));

                      // Check if the actual file is a jpeg image
                      if (($extName == '.jpg') || ($extName == '.jpeg')){
                        $thmbFile = $dirName.'/'.$fileMain.'_th.jpg';
                        // If a thumbnail dosnt exists tahn create a new one
                        if (!file_exists($thmbFile)){
                            imagejpeg(resizeImage($file,$thmb_width,$thmb_height)
                                     ,$thmbFile,80);
                        }
                    }
                  }
               }
           }
    }

}

function getNormalImage($file){
    $base = substr($file,0,strrpos($file,'_th.jpg'));
    if (file_exists($base.'.jpg')) return $base.'.jpg';
    elseif (file_exists($base.'.jpeg')) return $base.'.jpeg';
    else return "";
}

function displayPhotos(){
    global $columns,$dir;

    generateThumbnails();
    $act = 0;
    // Open the actual directory
    if ($handle = opendir("$dir")) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                    ++$act;
                    if ($act > $columns) {
                    	// See the top body tag for centering information - must center the outer div box
                        echo '</tr><tr valign="center">
                           <td align="center"><a class="photo-link" href="'.getNormalImage($file).'" target="_new">
                               <img src="'.$file.'" alt="'.$file.'"/></a></td>';
                        $act = 1;
                    } else {
                        echo '<td align="center"><a  class="photo-link" href="'.getNormalImage($file).'" target="_blank">
                           <img src="'.$file.'" alt="'.$file.'"/></a></td>';
                    }

                  }
              }
        }
    }
}
?>

<tr valign="center"><?php displayPhotos(); ?></table>

<p>&nbsp;</p>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-4304468-1");
pageTracker._initData();
pageTracker._trackPageview();
</script>
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.