tags:

views:

72

answers:

4

Is there a way to pull images from a directory and place them on a webpage and have links attached to those images that would take a person to a specific webpage associated with that image using PHP?

Thanks

A: 
<?php
  $directory = "imageDirectory"; // assuming that imageDirectory is in the same folder as the script/page executing the script
  $contents = scandir($directory);
    if ($contents) {
       foreach($contents as $key => $value) {
             if ($value == "." || $value == "..") {
                unset($key);
             }
       }
    }
        echo "<ul>";
    foreach($contents as $k => $v) {
      echo "<li><a href=\"$directory/" . $v . "\">link text</a></li>";
    }
        echo "</ul>";

?>

This should work, though foreach() can be -computationally- expensive. And I'm sure there must be a better/more-economical way of removing the relative-file-paths of . and .. in the first foreach()

David Thomas
A: 

something like this should do it :

    if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Files:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
    if(substr($file, -3) == 'jpg'){ //modify to handle filetypes you want
        echo "<a href='/path/to/files/".$file."'>".$file."</a>";
    }
    }

    closedir($handle);
}
Jesse
also, http://www.php.net/manual/en/function.readdir.php will help you. most of the above code is from that page.
Jesse
A: 

are you asking how to scan the directory or how to associate a list of images with urls?

the answer to the first question is glob() function

the second answer is to use an assoc array

$list = array('foo.gif' => 'bar.php', 'blah.gif' => 'quux.php');

and a foreach loop to output images and links

foreach($list as $src => $href) echo "<a href='$href'><img src='$src'></a>";
stereofrog
A: 

@ricebowl:

using PHP Version 5.2.9/apache 2.0/windows vista - I'm getting Parse error.

anyway, there is working solution:

$dir = "./imageDirectory";
$ext = array('.jpg','.png','.gif');

$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {

 print '<ul>';

 if(strpos($filename, '.') > 3)
 {
    print '<li><a href="'.$dir.'/'.$filename.'">'.str_replace($ext, '', $filename).'</a></li>';

 }

 print '</ul>';

}
daniel barucha
Ah? What's the error you're getting?
David Thomas
...ah, yeah. I'm not sure what I was doing to cause that to happen. Um, sorry about that. =/ (edited my post to correct the syntax/code)
David Thomas
change $directory = "imageDirectory"; to $directory = "./imageDirectory";that's it :)
daniel barucha