How to display all images if they exist in a folder PHP? - 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.

Related

how to display all images in a folder

I'm develop my websites and want to display all the images in a folder. I used the following code but occurred an error.
<?php
$sesi = Session::get('id');
$gambar = glob('archive_gambar/formulir/pendaftaran/'.$sesi.'/*');
for ($i=0; $i<count($gambar); $i++)
{
$single_image = $gambar[$i];
?>
<img src="<?php echo $single_image; ?>" class="img-responsive" style="margin-left: auto;margin-right: auto; margin-top: auto;margin-bottom: auto;width:75%;" alt="Tri">
<?php
}
?>
there is no error, the number of images is the same, but the picture does not appear.. like this
picture not appear
$dirname = "media/images/iconized/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
If the archive_gambar directory is at the root of the web site, try adding slash in front of the path
$gambar = glob('/archive_gambar/formulir/pendaftaran/'.$sesi.'/*');
if not, you must write the full path
Try with this, adjust the $dir variable to your needs:
/**
* This file: images.php
* This script read content of "images" directory as same level, and return filelist in array format
**/
$dir = "images/";
$images = array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if($dir){
if(in_array($file, array('.', '..')) == FALSE){
$images[] = $file;
}
}
}
closedir($dh);
}
}
/**
* Print array to browswer
*/
echo '<pre>';
print_r($images);
/**
* Iterate $images array in foreach loop and display images with img tag (need to adjust directory to your needs).
*/
foreach ($images as $key => $image){
echo '<img src="images/'.$image.'" class="img-responsive" alt="image_'.$key.'">';
}

php loop through files in subfolders in folder and get file paths

Im really new to PHP i searched google to find a correct script that loops through all subfolders in a folder and get all files path in that subfolder
<?php
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename. '<br/>';
}
?>
So i have folder 'posts' in which i have subfolder 'post001' in which i have two files
controls.png
text.txt
And the code above echos this
posts\.
posts\..
posts\post001\.
posts\post001\..
posts\post001\controls.png
posts\post001\text.txt
But i want to echo only the file paths inside these subfolders like this
posts\post001\controls.png
posts\post001\text.txt
The whole point of this is that i want to dynamically create divs for each subfolder and inside this div i put img with src and some h3 and p html tags with text equal to the .txt file so is this proper way of doing that and how to remake my php script so that i get just the file paths
So I can see the answers and they are all correct but now my point was that i need something like that
foreach( glob( 'posts/*/*' ) as $filePath ){
//create div with javascript
foreach( glob( 'posts/$filePath/*' ) as $file ){
//append img and h3 and p html tags to the div via javascript
}
//append the created div somewhere in the html again via javascript
}
So whats the correct syntax of doing these two foreach loops in php im really getting the basics now
See if this works :)
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if ((substr($file, -1) != '.') && (substr($file, -2) != '..')) {
echo $file . '<br/>';
}
}
<h1>Directory Listing</h1>
<?php
/**
* Recursive function to append the full path of all files in a
* given directory $dirpath to an array $context
*/
function getFilelist($dirpath, &$context){
$fileArray = scandir($dirpath);
if (count($fileArray) > 2) {
/* Remove the . (current directory) and .. (parent directory) */
array_shift($fileArray);
array_shift($fileArray);
foreach ($fileArray as $f) {
$full_path = $dirpath . DIRECTORY_SEPARATOR . $f;
/* If the file is a directory, call the function recursively */
if (is_dir($full_path)) {
getFilelist($full_path, $context);
} else {
/* else, append the full path of the file to the context array */
$context[] = $full_path;
}
}
}
}
/* $d is the root directory that you want to list */
$d = '/Users/Shared';
/* Allocate the array to store of file paths of all children */
$result = array();
getFilelist($d, $result);
$display_length = false;
if ($display_length) {
echo 'length = ' . count($result) . '<br>';
}
function FormatArrayAsUnorderedList($context) {
$ul = '<ul>';
foreach ($context as $c) {
$ul .= '<li>' . $c . '</li>';
}
$ul .= '</ul>';
return $ul;
}
$html_list = FormatArrayAsUnorderedList($result);
echo $html_list;
?>
Take a look at this:
<?php
$filename[] = 'posts\.';
$filename[] = 'posts\..';
$filename[] = 'posts\post001\.';
$filename[] = 'posts\post001\..';
$filename[] = 'posts\post001\controls.png';
$filename[] = 'posts\post001\text.txt';
foreach ($filename as $file) {
if (substr($file, -4, 1) === ".") {
echo $file."<br>";
}
}
?>
Result:
posts\post001\controls.png
posts\post001\text.txt
What this does is checking if the 4th last digit is a dot. If so, its an extension of three letters and it should be a file. You could also check for specific extensions.
$ext = substr($file, -4, 4);
if ($ext === ".gif" || $ext === ".jpg" || $ext === ".png" || $ext === ".txt") {
echo $file."<br>";
}

PHP/ read from folder

I have the next code:
<?php
$path = 'imgsFor';
$files_array = scandir($path);
for ($x=0; $x<=4; $x++)
{
echo '<img src="imgsFor/$files_array[$x]" <br>';
}
?>
In order to display all images in the folder imgsFor.
For some reason, I see the just boxes and not the actual images.
What can be the reason?
The best way for me is to use glob function:
foreach (glob($path) as $filename) {
echo '<img src="' . $path . '/' . $filename . '"/><br/>';
}
You messed up some things. Your correct script would be
<?php
$path = 'imgsFor/';
$files_array = scandir($path);
foreach($files_array as $f) {
if(is_dir($path . $f) === false)
continue;
echo '<img src="' , $path , $f , '"><br>';
}
/* EOF */
The reason is that your URL is invalid. Your variable wont echo out if you use single quotes. You also forgot to end the tag. Try this:
echo "<img src='http://yourwebsite.com/imgsFor/{$files_array[$x]}'/><br/>";
Please check you directory path and use is_dir which returns false when the file doesn't exist. you can try like this
$path = 'imgsFor';
$scan = scandir($path);
foreach($scan as $file)
{
if (!is_dir($path))
{
echo $file.'\n';
}
}

Using Logical AND Operators && in foreach php

I have the following code for an image gallery :
$directory = 'some path';
$thumbs_directory = 'some path';
foreach (glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file)
foreach (glob($thumbs_directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file2)
{
if($file=='.' || $file == '..') continue;
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));
$title = basename($file);
$title = htmlspecialchars($title);
$title = str_replace("_"," ",$title);
$nomargin='';
if(($i+1)%4==0) $nomargin='nomargin';
echo '
<div class="pic '.$nomargin.'" style="background:url('.$file2.') no-repeat 50% 50%;">
'.$title.'
</div>';
$i++;
}
I need to combine these foreach statements through the Logical AND operator && so that both conditions are satisfied at the same time. Is it possible ? I've tried numerous times, but always ends up in a Syntax error.
Please note that I need $file and $file2 variables defined perfectly. That is only the way for the thumbnails to associate with the images properly.
Can you not simply refactor the meaty logic into a common function, and then call it twice?
For example:
function doSomething($directory) {
foreach (glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file) {
/* Whatever */
}
}
...
doSomething($directory);
doSomething($thumbs_directory);
Based on your description, if you want to loop over the image files that exist in both directories, you should look into using php's array_intersect().
$directory = 'some path';
$thumbs_directory = 'some path';
$files_in_dir1 = glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$files_in_dir2 = glob($thumbs_directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$files_in_both_dirs = array_intersect($files_in_dir1, $files_in_dir2);
foreach ($files_in_both_dirs as $filename) {
// Code
}
To map images to their respective thumbnail images, I would rather choose a different approach:
$directory = 'some path';
$thumbs_directory = 'some path';
// Get all images
$images = glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
// Iterate over all images
foreach ($images as $image) {
// Construct path to thumbnail
$thumbnail = $thumbs_directory .'/'. basename($image);
// Check if thumbnail exists
if (!file_exists($thumbnail)) {
continue; // skip this image
}
// .. continue as before
echo '
<div class="pic '.$nomargin.'" style="background:url('.$thumbnail.') no-repeat 50% 50%;">
'.$title.'
</div>
';
}
}

Echo php array value

I have the following code that reads the content of a folder
PHP Code:
<?
//PHP SCRIPT: getimages.php
header('content-type: application/x-javascript');
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="./images") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";' . "\n";
$curimage++;
}
}
closedir($handle);
}
sort($files);
return($files);
}
echo 'var galleryarray=new Array();' . "\n"; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
which spits out this the following code:
var galleryarray = new Array();
galleryarray[0] = "image1.jpg";
galleryarray[1] = "image5.jpg";
galleryarray[2] = "image2.jpg";
galleryarray[3] = "image4.jpg";
galleryarray[4] = "image8.jpg";
galleryarray[5] = "image7.jpg";
galleryarray[6] = "image0.jpg";
galleryarray[7] = "image3.jpg";
galleryarray[8] = "image6.jpg";​
Now in my html file I want to echo something like
<img src="images/image0.jpg" />
<img src="images/image1.jpg"/>
...
...
How can I do that?
foreach($galleryarray as $img) {
echo "<img src='images/$img' />";
}
maybe this help u
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
if($handle = opendir("./images")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ ?>
<img src="/images/<?php echo $file; ?>">
<?php
}
}
}
assuming that you want to sort image name by value and then show the images. you first need to sort values by using function "asort"
asort($galleryarray);
foreach ($galleryarray as $key => $val) {
echo "<img src='images/{$val}'/>"
}
if you want to print and array
1) print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
2) use var_dump($array) to get more information of the content in the array like datatype and length.
3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website http://in3.php.net/manual/en/control-structures.foreach.php
Try changing the echo line in the function to this:
echo '<img src="images/' . $file . '" />' ;
Hope this will help :)
OR
Outside the function, use it like this:
$images = returnimages(); //will get the array containing the images
foreach($images as $img)
{
echo '<img src="images/' . $img . '" />';
}
Also, you have to include this line inside the if condition in the while loop:
$files[] = $file; //insert the file into the array. This array is what we are going to return from the function
Update
I have tested this code and it's working:
//PHP SCRIPT: getimages.php
header('content-type: application/x-javascript');
function returnimages($dirname="./images") {
$pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)"; // http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression/
$files = array();
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(preg_match($pattern, $file)){ //if this file is a valid image
$files[] = $file;
}
}
closedir($handle);
}
//sort($files); // http://php.net/manual/en/function.sort.php
natcasesort($files); // case insensitive "natural order" algorithm :: http://php.net/manual/en/function.natcasesort.php
return($files);
}
$images = returnimages(); //will get the array containing the images
foreach($images as $img)
{
echo '<img src="images/' . $img . '" />';
}
In my images folder, I have put 5 files for testing. And upon running it, it would give the following:
<img src="images/a.jpg" />
<img src="images/ba.jpg" />
<img src="images/ca.jpg" />
<img src="images/Copy (3) of a.jpg" />
<img src="images/Copy (4) of a.jpg" />

Categories