Reputation: 2015
I'm not sure exactly where this script will be running, so it must be able to access this directory from anywhere.
I'm trying to create a list of images by getting the image file names from a directory, filtering them until I only have the image formats I want, then displaying them using an <img>
tag.
The first bit went really well. Outputting the HTML is proving to be a problem.
While I can use $_SERVER["DOCUMENT_ROOT"] to work with the directories in PHP, it's problematic to output that value as part of the path in the
tag's
src` attribute.
Here is my current code:
$unkwown_files = scandir($_SERVER['DOCUMENT_ROOT'] . "/path/images");
foreach($unkwown_files as $file) {
$exploded_filename = explode(".", $file);
$file_type = array_pop($exploded_filename);
$accepted_filetypes = [
"png",
"jpg",
"gif",
"jpeg"
];
$picture_names = [];
if (in_array($file_type, $accepted_filetypes)) {
$picture_names[] = $file;
}
}
foreach($picture_names as $picture) {
$path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images" . $picture;
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
Upvotes: 0
Views: 47
Reputation: 33813
A slightly different approach for you that filters files by extension from the outset.
$dir = $_SERVER['DOCUMENT_ROOT'] . "/path/images/";
/*
glob() searches for files/paths that match the pattern in braces and returns the results
as an array.
The '*' is a wildcard character as you would expect.
The flag 'GLOB_BRACE' expands the string so that it tries to match each
( From the manual: GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c' )
*/
$col = glob( $dir . "*.{jpg,png,gif,jpeg}", GLOB_BRACE );
/*
Iterate through the results, with each one being the filepath to the file found.
As the glob() function searched for the required types we don't need to check
if they are in the allowed types array.
Because you do not wish to display the fullpath to the image, a relative path is
preferred - thus we remove, from the path, the document root.
*/
foreach( $col as $index => $file ){
$path_to_image = str_replace( $_SERVER['DOCUMENT_ROOT'], '', $file );
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
Upvotes: 1
Reputation: 583
Try this out
foreach($picture_names as $picture) {
$path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images/" . $picture;
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
Upvotes: 0