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
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
<?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()
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);
}
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>";
@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>';
}