PHP dynamic gallery problem

2019-08-14 07:34发布

问题:

I'm trying to create a dynamic image gallery script, so that a client, once I'm done with the site, can upload images via FTP and the site will update automatically. I'm using a script I found on here, but I cannot get it to work for the life of me. The PHP writes information, but will never actually write out the images it's supposed to find in the directory. Not sure why. Demo here and you can see the working code (without PHP) here.

<?php 
function getDirTree($dir,$p=true) {
    $d = dir($dir);$x=array();
    while (false !== ($r = $d->read())) {
        if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) {
                $x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false));
        }
    }

    foreach ($x as $key => $value) {
        if (is_dir($dir.$key."/")) {
                $x[$key] = getDirTree($dir.$key."/",$p);
        }
    }

    ksort($x);
    return $x;
}
$path = "../images/bettydew/";
$tree = getDirTree($path);

echo '<ul class="gallery">';

foreach($tree as $element => $eval) {
    if (is_array($eval)) {
        foreach($eval as $file => $value) {
                if (strstr($file, "png")||strstr($file, "jpg")||strstr($file, "bmp")||strstr($file, "gif")) {
                        $item = $path.$file;
                        echo '<a href="javascript:void(0);"><img src="'.$item.'" alt="'.$item.'"/></a>';
                }
        }
    }
}

echo '</ul>';
?>

回答1:

path problem and a recursion problem in the sub-directories.

perhaps try this:

<?php
$path = "./images/bettydew/";
$file_array = array ();
readThisDir ( $path, &$file_array );

echo '<ul class="gallery">';
foreach ( $file_array as $file )
{
  if (strstr($file, "png")||strstr($file, "jpg")||strstr($file, "bmp")||strstr($file, "gif"))
  {
  list($width, $height) = getimagesize($file);
  echo '<li><a href="javascript:void(0);"><img src="'.$file.'" width="'.$width.'" height="'.$height.'" alt="'.$file.'"/></a></li>';
  }
}
echo '</ul>';

  function readThisDir ( $path, $arr )
  {
    if ($handle = opendir($path)) 
    {
        while (false !== ($file = readdir($handle))) 
        {
            if ($file != "." && $file != "..") 
            {
              if (is_dir ( $path."/".$file ))
              {
                readThisDir ($path."/".$file, &$arr);
              } else {
                $arr[] = $path."/".$file;
              }  
            }
        }
        closedir($handle);
    }
  }
?>


回答2:

Either Your path is mistake... it caused me similar error when i feed wrong path to the $path variable.

Or you do not have read permission on that directory... check the permissions too

And remember to check '/' at the end of your path as without it your code cannot do recursive search inside the child directory...

And finally your code will not give the correct file path of the files of sub-directory while writing output... so check it too...