Lets say I have 4 jpg files in a directory that will only ever contain jpg files. The number of files may change, the naming convention will always be Name-file.jpg
Bob-file.jpg
Tom-file.jpg
Dave-file.jpg
Douglas-file.jpg
I am trying to come up with a php script that will look at the directory and display each image (as in viewing the picture, not just listing the filename) in the web browser and also add the persons name along side it so I can see who it is.
I have tried playing with arrays and loops but can't get anything remotely close (I'm new to PHP) Thanks!!
CodePudding user response:
You'll want something roughly along these lines. Using a directory iterator to get all the filenames and then using a regular expression to extract the name from the filename.
foreach ((new DirectoryIterator('./path/to/image/dir')) as $file) {
if (!$file->isDot() && preg_match('#^(. )\-file\.jpg$#uD', $file->getFilename(), $details) === 1) {
printf('<div><img src="%s" alt="Picture of %s">%s</div>',
htmlentities( '/web/path/to/images/' . $details[0] ),
htmlentities( $details[1] ),
htmlentities( $details[1] )
);
}
}
CodePudding user response:
<?php
$directory_to_read_from = './imgage_directory';
if ($handle = opendir($directory_to_read_from))
{
while (false !== ($entry = readdir($handle)))
{
if ($entry != "." && $entry != "..")
{
$name = explode('-', $entry);
echo '<h1>' . $name[0] . "</h1><img src='$directory_to_read_from/$entry' /><br>";
}
}
closedir($handle);
}
OUTPUT: