Post images from directory php [duplicate] - php

This question already has answers here:
PHP file listing multiple file extensions
(5 answers)
Closed 9 years ago.
I am very new to php and I would like to iterate through an images directory in the root folder and post these images to a webpage. I am using the following code to do so:
<?php
$dir = "images/*.jpg";
$images = glob( $dir );
foreach( $images as $image ):
echo "<img src='" . $image . "' />";
endforeach;
?>
My question is how can I modify this code to post more than .jpg images, such as .gif and jpg with the .jpeg extension without creating multiple directory variables?
Also, is there a more efficient way to post these images?
Thank you very much!

The non clever brute force way to do this would be to just run the loop for all different image types.
$dir = "images/*.jpg";
$images = glob( $dir );
foreach( $images as $image ):
echo "<img src='" . $image . "' />";
endforeach;
$dir = "images/*.png";
$images = glob( $dir );
foreach( $images as $image ):
echo "<img src='" . $image . "' />";
endforeach;
$dir = "images/*.gif";
$images = glob( $dir );
foreach( $images as $image ):
echo "<img src='" . $image . "' />";
endforeach;
etc...

An elegant way would be creating an array and then iterate it.
<?php
$imgs = array("images/*.jpg","images/*.gif","images/*.pnj");
foreach( $imgs as $type ){
$images = glob( $type );
foreach( $images as $image ):
echo "<img src='" . $image . "' />";
endforeach;
endforeach;
?>

As you are building an Array ($images is an array) you can push new files to this array.
$file_extensions = ['jpg', 'png'];
$images_total = [];
foreach ( $file_extensions as $extension ) {
$dir = "images/*." . $extension;
$images = glob( $dir );
foreach $images as $image {
$images_total[] = $image;
}
}
And now use your final code:
<?php
foreach( $images_total as $image ):
echo "<img src='" . $image . "' />";
endforeach;
?>
I didnt test it, but this is an idea :)
I reply appeared while I typed: As a difference, in my method you get to build an array containing every single file in the folder before start printing HTML. This may allow you to shuffle or maybe manipulate the array before outputting to the user :)

Related

How to display all images if they exist in a folder PHP?

I have a PHP script that scans a specified Movie directory then displays it styled on a webpage using for loop and php. The code is below. I tried using glob but once I have all the images in an array how do I compare them to the array with all of the movies then if the image and the movie folder match to display the image with the correct name?
<?php
// set dir to the directiry you want to index
$dir = 'Movies/';
// scanning the directory you set
$scan = scandir($dir);
// I have this value at 11 because the first movie shows up
// in the 11th file in the array
$file = 11;
// This then removes the first useless files from our array
$scanned = array_slice($scan, $file);
// gets the amount of files
$FileNum = count($scanned);
// display all images and fanart
$images = glob('*.jpg');
// for loop that goes through the array
for ($i = 0; $i <= $FileNum; $i++) {
// gives the class for styling
echo '<li class="image">';
this is problem bit
// check if there is fanart/images in the folders
if (file_exists($dir . $scanned[$i] . $images)) {
// if there is images display them styled
echo '<img id="box1" src="' . $dir . $scanned[$i] . '*.jpg' . '" width="280" height="150" />';
} else {
// if not then display default image
echo '<img id="box1" src="http://placehold.it/280x150" width="280" height="150" />';
}
// make the box clickable to where the folder is located
echo '<a href="'. $dir . $scanned[$i] .'">';
// display the name of the movie and some JS
echo '<span class="text-content"><span>' . $scanned[$i] .'<br><br><i class="fa fa-4x fa-play-circle-o"></i><br><br><i class="fa fa-chevron-down" onclick="openNav()" aria-hidden="true"></i></span></span> </a>';
}
The file structure is as follows
`MOVIES---
\--random movies
\--mp4 and .jpg files`
To clarify my question is - Is there a way to check if a file exists, and if it does then put it in an array? I've tried using glob but that can't check if the file exists.
Well there is an * in your echo i don't think it needs to be there.
And if your movie directory gets updated, or the images. Then your script does not work anymore. Because of the hard slicing (11th file).
Maybe this will work for you:
<?php
// movies
$dir = "movies/";
$files = scandir($dir);
$movies = array();
$images = array();
foreach ($files as $file) {
// check for the mime type:
$mime = mime_content_type($dir . $file);
$type = substr($mime, 0,5);
$filename = pathinfo($dir . $file, PATHINFO_FILENAME);
if ($type == "video") $movies[] = $file;
if ($type == "image") $images[] = $filename;
}
foreach ($movies as $movie) {
$placeholder = true;
foreach($images as $image) {
if (strpos($movie, $image) !== false) {
$placeholder = false;
continue;
}
}
if ($placeholder) {
echo $movie . " - placeholder<br>";
} else {
echo $movie . " - image<br>";
}
}
It works with the mime-type.

How can I combine two arrays for a loop?

I'm stuck on this for a while now: I'm trying to combine two arrays, one is every image in a folder, and the other one is the description of the picture from the SQL Database. In the database I've added the filename and the apartment name. To make my query work I need it to be in a loop, but to show the results of my query, it needs to become a loop, so I would think it must be possible to combine it right? But I can't seem to figure out how to combine these two arrays in a loop. I've tried with two loops and this is what I've got:
<?php
$directory = "images/photos/";
$images = glob('images/photos/*.{jpg,png,gif}', GLOB_BRACE);
foreach ($images as $image) {
$sqlaa = "SELECT * FROM `afbeelding` WHERE filename = ' . $image . '";
$titles = mysqli_query($link, $sqlaa);
while ($row = $titles->fetch_array()) {
echo '<form action="" method="post"><li>
<a href="' . $image . '" title="' . $row['apartment'] . '" >
<img style="width:150px;height:150px;" src="' . $image . '" />
</a>
</li>';
}
}
?>
If anyone knew, that'd be great!
Thanks in advance
You can try making the loop over the data and then check the image in the loop, this could be faster and avoids using a query inside a loop.
<?php
$directory = "images/photos/";
//$images = glob('images/photos/*.{jpg,png,gif}', GLOB_BRACE);
$sqlaa = "SELECT filename,apartment FROM `afbeelding`";
$titles = mysqli_query($link, $sqlaa);
while($row = $titles->fetch_array())
{
$image=$row["filename"];
if (file_exists($directory.$image)){
echo '<form action="" method="post"><li>
<a href="'.$image.'" title="' . $row['apartment'] . '" >
<img style="width:150px;height:150px;" src="'.$image.'" />
</a>
</li>';
}
}
?>
I don't know if the image is stored using the full relative path "images/photos/img.png" or the base filename only "img.png".
If the data in afbeelding is huge, you can improve the sql query using an IN filter
function imageNames($item){
return "'$item'";
}
$images = glob('images/photos/*.{jpg,png,gif}', GLOB_BRACE);
$names=array_map("imageNames",$images);
$filter_names=implode(",",$names);
$sqlaa = "SELECT filename,apartment FROM `afbeelding` WHERE filename IN ($filter_names)";
And then proceed with the loop, without checking files.
How about... going about it differently.
You already have the filenames in database.
So just poll your database with your available data, and then just echo it.
I'm assuiming it's stored as images/photos/filename.jpg in your database.
But without a data sample as is in your database I can't speculate more.
$directory = "images/photos/";
foreach ($images as $image) {
$sqlaa = "SELECT * FROM `afbeelding` WHERE filename like '%images/photos/%'";
$titles = mysqli_query($link, $sqlaa);
while ($row = $titles->fetch_array()) {
echo '<form action="" method="post"><li>
<a href="' . $image . '" title="' . $row['apartment'] . '" >
<img style="width:150px;height:150px;" src="' . $row['filename'] . '" />
</a>
</li>';
}
}
first: loops on db-calls are not really best practice..
A possible result to your question:
<?php
$directory = "images/photos/";
$images = glob('images/photos/*.{jpg,png,gif}', GLOB_BRACE);
$images = array_flip($images);
// get data first
foreach($images as $image => $v) {
$sqlaa = "SELECT * FROM `afbeelding` WHERE filename = ' . $image . '";
$titles = mysqli_query($link, $sqlaa);
if ($title->num_rows == 1) {
$row = $titles->fetch_array();
$images[$image] = $row['apartment'];
} else {
$images[$image] = '';
}
}
// render data
foreach ($images as $filename => $description) {
echo '<form action="" method="post"><li>
<a href="'.$filename.'" title="' . $description . '" >
<img style="width:150px;height:150px;" src="'.$filename.'" />
</a>
</li>';
}
?>
Not really nice, but plain simple..

How to make last uploaded images appear first in foreach loop

I have this code that shows uploaded images:
<?php
$dir = "img/*.jpg";
$images = glob( $dir );
foreach( $images as $image ):
echo "<img src='" . $image . "' />";
endforeach;
?>
but I need my last uploaded image to appear first in line. I know it's right there in front of me, but I can't see it. How do I do that?
Try reversing the array before your foreach.
<?php
$dir = "img/*.jpg";
$images = glob( $dir );
$images = array_reverse($images);
foreach( $images as $image ):
echo "<img src='" . $image . "' />";
endforeach;
?>
A safer bet would be to use the filemtime() function to get the modification time of each file and sorting according to that. See this code:
<?php
$dir = "img/*.jpg";
$images = glob( $dir );
//Add this portion
foreach( $images as $image ) {
$imagesModTimeArray[filemtime($image)] = $image;
}
krsort($imagesModTimeArray);
$images=array_values(imagesModTimeArray);
//New Portion End
foreach( $images as $image ):
echo "<img src='" . $image . "' />";
endforeach;
?>

don't show the same images

this script show 50 random images
that change turning on themselves.
but sometimes show the same images
how don't show the same images?
my code
<?php
$all_images = glob("wp-content/themes/mysite/img-company/{*.jpg, *.JPG, *.JPEG, *.png, *.PNG}", GLOB_BRACE);
$images = glob("wp-content/themes/mysite/img-company/{*.jpg, *.JPG, *.JPEG, *.png, *.PNG}", GLOB_BRACE);
shuffle($all_images);
foreach ($all_images as $index => $image ) {
if ($index == 50) break; // Only print 50 images
$image_name = basename($image);
$randomImage = $images[array_rand($images)];
echo "<li><img src='/wp-content/themes/mysite/img-company/{$image_name}' /><img src='/$randomImage' /></li>";
}
?>
The obvious way would be to delete a presented image from the array:
$randomImage = $images[array_rand($images)];
$images = array_diff($images, array($randomImage));
Another solution: Simply use unset for removing element from array like this:
$random = array_rand($images);
$randomImage = $images[$random];
unset($images[$random]);

php directory iterator, shuffle images

<?php
$dir = new DirectoryIterator('../images/main_body_image/');
foreach ($dir as $file)
{
$images [] = array (
$file->getPathname() . "\n";
$file->getFilename(). "\n";
);
}
?>
shuffle($images);
Can you help me with the code above? I want to add images to an array using DirectoryIterator, and then shuffle images to generate randomized images. Thank you for your valuable inputs.
This depends on what you are doing with the images, and what path your in at the time, but the following will put their full pathname into an Array.
<?php
$dir = new DirectoryIterator('../images/main_body_image/');
foreach($dir as $file){
$images[] = $file->getPathname();
}
shuffle($images); $imgs = '';
foreach($images as $v){
$imgs .= "<img scr='http://{$_SERVER['SERVER_NAME']}/$v' alt='randomImage' />";
}
//put the below wherever you want in your code
echo $imgs;
?>

Categories