简体   繁体   中英

Pull Images from directory - PHP

I am trying to pull images simply from my directory /img and load them dynamically into the website into the following fashion.

            <img src="plates/photo1.jpg">

That's it. It seems so simple but all of the code I have found basically doesn't work.

What I have that I am trying to make work is this:

   <?php
   $a=array();
   if ($handle = opendir('plates')) {
while (false !== ($file = readdir($handle))) {
   if(preg_match("/\.png$/", $file)) 
        $a[]=$file;
else if(preg_match("/\.jpg$/", $file)) 
        $a[]=$file;
else if(preg_match("/\.jpeg$/", $file)) 
        $a[]=$file;

}
closedir($handle);
   }

 foreach($a as $i){
echo "<img src='".$i."' />";
 }
 ?>

This can be done very easily using glob() .

$files = glob("plates/*.{png,jpg,jpeg}", GLOB_BRACE);
foreach ($files as $file)
    print "<img src=\"plates/$file\" />";

You want your source to show up as plates/photo1.jpg , but when you do echo "<img src='".$i."' />"; you are only writing the file name. Try changing it to this:

<?php
$a = array();
$dir = 'plates';
if ($handle = opendir($dir)) {
  while (false !== ($file = readdir($handle))) {
    if (preg_match("/\.png$/", $file)) $a[] = $file;
    elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
    elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
  }
  closedir($handle);
}
foreach ($a as $i) {
  echo "<img src='" . $dir . '/' . $i . "' />";
}
?>

You should use Glob instead of opendir/closedir. It's much simpler.

I'm not exactly sure what you're trying to do, but you this might get you on the right track

<?php
foreach (glob("/plates/*") as $filename) {

    $path_parts = pathinfo($filename);

    if($path_parts['extension'] == "png") {
        // do something
    } elseif($path_parts['extension'] == "jpg") {
        // do something else
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM