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>
';
}
}
Related
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.
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>";
}
I'm trying to build a gallery for a friend, using PHP. Currently my script imports all the images from a "gallery" folder, and it displays them alphabetically, using automatically generated thumbnails and fancybox plugin.
Is it posible to sort them by date? It doesn't matter if it's the date when they were taken or the date when they were last modified. The code I use is below. Thanks in advance!
<?php
$path = 'gallery/';
$files = scandir('gallery/');
?>
<ul>
<?php foreach ($files as $file){
if ($file == '.' || $file == '..'){
echo '';
} else {
?>
<li><a class="fancybox" rel="group" href="<?php echo $path . $file; ?>"><img src="scripts/timthumb.php?src=<?php echo $path . $file; ?>&h=194&w=224&zc=1&q=100" /></a></li>
<?php } }?>
</ul>
this php function sorts your file by the last date it was modified.
Don't forget to put in the ignored files array which files you want to be ignored.
function scan_dir($dir) {
$ignored_files = array()
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file,$ignored_files) {
$files[$file] = filemtime($dir.'/'.$file);
}
}
arsort($files);
$files = array_keys($files);
if(is_null($files))
return false;
return $files;
}
You can refactor it a bit this was made really quicly. Hope this will work
<?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;
?>
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" />