PHP loop with dyamic images from a folder list - php

I have a folder called loop-images which has a set of images. I also have the php loop below:
foreach ($feed as $feed_id => $feed_title){
echo '<img src="/loop-images/01.jpg" border="0"><br>';
echo ''.$feed_title.'';
}
In the loop I have a fixed image, However I am looking to use the image dynamically from the loop-images folder. So basically, on the first loop it should use the first image and so on. If it runs out of images in the loop then it starts from the first image again.
Any ideas how I can achieve this?
Thanks

Here is something which you can try
$directory = "/loop-images"; // path to loop images folder
$images = glob($directory . "*.jpg");
$imagescounter = 0; foreach ($feed as $feed_id => $feed_title){
if($imagescounter>count($images)){
$imagescounter = 0;
}
echo '<img src="/loop-images/'.$images[$imagescounter].'.jpg" border="0"><br>';
echo ''.$feed_title.'';
$imagescounter++;
}

Maybe what you're trying to accomplish is something like that.
Using the scandir function and a regex to match all images using preg_match php function
foreach(scandir('/path/to/loop-images/') as $key => $file) {
if (preg_match('/[\s\S]+\.(png|jpg|jpeg|tiff|gif|bmp)/iu', $file)) {
echo '<img src="loop-images/' . $file . '" border="0"><br>';
}
}

Related

Display All .MP3 Files From A Folder In An Audio Tag

How can I get all audio files from a folder and display it in Audio Tags?
What I Have Tried
$sPath = 'music/favorite/*.mp3';
foreach (glob($sPath) AS $mp3) {
print $mp3 . PHP_EOL;
}
You can do it inside of the foreach. If you just want to echo the files, just do it like this:
foreach (glob($sPath) AS $mp3) {
echo '<audio>';
echo '<source src="'.$mp3.'" type="audio/mpeg">';
echo '</audio>';
}
Maybe you need to adjust the path of your $mp3 var.
It's just a sample. Please don't blame me because I didn't tested this.
Hope this helps.

Where does "." (dot) come from when using PHP ´scandir´

I'm a bit confused.
I'm building a PHP function to loop out images in a specified dir.
PHP
$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$thumbnails = scandir($dir);
print_r($thumbnails);
foreach ($thumbnails as $value) {
echo "<img src='".$dir.$value. "'>";
}
array
(
[0] => .
[1] => ..
[2] => bjornc.jpg
[3] => test_bild3.jpg
)
HTML
<img src='bilder/22159/thumbnail/.'>
<img src='bilder/22159/thumbnail/..'>
<img src='bilder/22159/thumbnail/bjornc.jpg'>
<img src='bilder/22159/thumbnail/test_bild3.jpg'>
How can i get rid of theese dots?
I guess it´s the directorie dots..
UPDATE
The most easy way was found in php.net manual
$thumbnails = array_diff(scandir($dir), array('..', '.'));
The dot directory is the current directory. Dot-dot is the parent directory.
If you want to create a list of files in a directory you should really skip those two, or really any directory starting with a leading dot (on POSIX systems like Linux and OSX those are supposed to be hidden directories).
You can do that by simply check if the first character in the file name is a dot, and if it is just skip it (i.e. you continue the loop).
You can skip it by using in_array as
foreach ($thumbnails as $value) {
if (!in_array($value, array(".", ".."))) {
echo "<img src='" . $dir . $value . "'>";
}
}
You can also use this
foreach ($thumbnails as $value) {
if ( $value !='.' && $value !='..')
{
echo "<img src='".$dir.$value. "'>";
}
}
If you are looking for a specific file type, such as images, you are better off using glob.
It allows you to pass a pattern of extensions.
This way you can be sure you fetch only the files you are looking for.
Example for multiple file types, .jpg and .png
$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$files = glob("*.{jpg,png}", GLOB_BRACE);
print_r($files);
GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
Example for a single file type, .jpg
$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$files = glob("*.jpg");
print_r($files);
they are directory and parent directory, they can be removed with following code:
<?php
$dir = "downloads/";
if (is_dir($dir)){
if ($dir_handler = opendir($dir)){
while (($file = readdir($dir_handler)) !== false){
if ($file!="."&&$file!="..") {
//your code
}
}
closedir($dir_handler);
}
}
?>
#joachim Pileborg answer is correct, By the way you can also use glob()
$thumbnails = glob("$dir/*.jpg");
foreach ($thumbnails as $value) {
echo "<img src='$value'/>";
}

check if filename is like string in php for displaying images

I am trying to get all images from a folder with php. It works fine. Now i wanna check if a certain image exists, and if so don't display it.
This is my basic code with works fine:
foreach (glob("Bilder/Spectrum/*.png") as $filename) {
$filenameDienst = explode("_", $filename);
echo "<a href='Dienste?d=".$filenameDienst[1]."#tabs-2'> <img class='loopimage' src='".$filename."'> </a>";
}
Now i wanna check for the image name "MB_default_Spectrum.png" and if it exists don't display it.
I have tried this:
foreach (glob("Bilder/Spectrum/*.png") as $filename) {
$filenameDienst = explode("_", $filename);
if ($filename != "MB_default_Spectrum.png") {
echo "<a href='Dienste?d=".$filenameDienst[1]."#tabs-2'> <img class='loopimage' src='".$filename."'> </a>";
}
}
But it did not work.. it is still displaying. What is wrong here? Thanks
glob returns an array of the paths matching the given pattern, not just the filenames. Looking at your code, the condition should then be:
if ($filename != "Bilder/Spectrum/MB_default_Spectrum.png")
Also, I personally prefer the following code (I find it cleaner):
$results = glob('path/to/dir/*.png');
foreach ($results as $filename)
// Skip specific file
if ($filename === 'path/to/dir/secretNuclearLaunchCodesAsImage.png')
continue;
echo $filename
}

PHP to post links to sub directories & php to display images

I'm very basic when it comes to PHP.
With my website, I have a directory called "uploads"
Within "uploads" I have 3 folders "Example1" "Example2" and "Example3"
Within each of the folders, they contain images.
I need to know how to use php to create a navigation for every sub directory.
So that if I add a new folder "Example4" it will give a navigation like:
Select what section you're looking for:
Example1 | Example2 | Example3
and if I later add new folders add them to the navigation.
EX:
Example1 | Example2 | Example3 | Example4 | Example5
Then once they click the link to go into the folder, have a code that displays all the images in that folder.
So far I have:
<?php
$files = glob("uploads/*.*");
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="/'.$num.'">'."<p>";
}
?>
but it will only display the images in the upload directory, not the images in Example1 and so on.
How on earth would I go about doing this? I'm doing it for a school project and have two weeks to complete it, but I am so lost. I only have knowledge with CSS, HTML, and the only PHP I know is php includes, so any help would be appreciated.
Since it seems that you are familiar with globs a bit, here is an example using the "glob" function. You can see a basic working example of what you are looking for here:
http://newwebinnovations.com/glob-images/
Here is how I have the example set up:
There are two PHP files, one is index.php and the other is list-images.php.
There is also a folder for images two subfolders that have images inside of them.
index.php is the file that finds the folders in the images folder and places them in a list with links list-images.php which will display the images inside of the folder:
$path = 'images';
$folders = glob($path.'/*');
echo '<ul>';
foreach ($folders as $folder) {
echo '<li>'.$folder.'</li>';
}
echo '</ul>';
The links created above have a dynamic variable created that will pass in the link to the list-images.php page.
Here is the list-images.php code:
if (isset($_GET['folder'])) {
$folder = $_GET['folder'];
}
$singleImages = array();
foreach (glob($folder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $image) {
$imageElements = array();
$imageElements['source'] = $image;
$singleImages[$image] = $imageElements;
}
echo '<ul>';
foreach ($singleImages as $image) {
echo '<li><img src="'.$image['source'].'" width="400" height="auto"></li>';
}
echo '</ul>';
The links created here will link you to the individual images.
To get files of every specific folder ,pass it throw a get variable that contains folder's name,an then scan this folder an show images ,url should be like this :
listImages.php?folderName=example1
To have menu like what you want :
<?php
$path = 'uploads/' ;
$results = scandir($path);
for ($i=0;$i<count($results);$i++ ) {
$result=$results[$i];
if ($result === '.' or $result === '..') continue;
if (is_dir($path . '/' . $result)) {
echo "<a href='imgs.php?folderName=$result'>$result</a> ";
}
if($i!=count($results)-1) echo '|'; //to avoid showing | in the last element
}
?>
And here is PHP page listImages that scan images of a specific folder :
<?php
if (isset($_GET['folderName'])) $folder=$_GET['folderName'];
$path = 'uploads/'.$folder.'/' ;
$images = glob($path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($images as $image) {
echo "<img src='$image' />";
}
?>
First of all, do read more PHP manual, for directory related: opendir, for files related: fopen
The following code is basically re-arranging the example code provided in opendir. What it does:
A scan_directory function to simply check if directory path is valid and is a directory, then proceed to do a recursive call if there's a child directory else just print out the file name.
The first if/else condition is just to ensure the base directory is valid.
I'll added ul and li to make it slightly more presentable.
$base_dir = 'upload';
if (is_dir($base_dir))
scan_directory($base_dir);
else
echo 'Invalid base directory. Please check your setting.';
// recursive function to check all dir
function scan_directory($path) {
if (is_dir($path)) {
if ($dir_handle = opendir($path)) {
echo '<ul>';
while (($file = readdir($dir_handle)) !== false) {
if ($file != '.' && $file != '..') {
if (is_dir($path . '/' . $file)) {
echo '<li>';
echo $file;
scan_directory($path . '/' . $file);
echo '</li>';
}
else
echo "<li>{$file}</li>";
}
}
echo '</ul>';
}
}
}
create image as subdirectory name with image name and save it in database
example:
subdirectory name: example2
image name: image.jpg
store image name in db as "example2/image.jpg"

php filter array of image names and show missing #2x retina images

I have a folder of a lot of images for in iPad app. Trying to create an automated php script to check to see if all the images that are in the folder have a paired non-retina and retina image set. If the retina image is not present, display a message saying something like: "Missing: $filename" where $filename is the value... I am coming up short on how to do a compare of the array of images grabbed via glob():
First i get the images from the folder that are jpg or png:
$images = glob("ipad/{*.jpg,*.png}", GLOB_BRACE);
Now i want to check this array of images to show the missing #2x image sets... I was reading that you could use array_filter but don't quite get how to do this...
Any ideas how to achieve this and then echo them out with a foreach "Missing: $filename"
You can use the following:
$path = __DIR__;
$all = glob("$path/*.{jpg,png}", GLOB_BRACE);
$normal = $retina = array();
// Group Images
foreach($all as $v) {
strpos($v, '#2x') === false and $normal[basename($v)] = $v;
strpos($v, '#2x') !== false and $retina[basename($v)] = $v;
}
foreach($normal as $image) {
$v = pathinfo($image);
$name = $v['filename'] . '#2x.' . $v['extension'];
if (! isset($retina[$name])) {
echo "Missing: $name\n";
}
}
Something like this should do:
var_dump(array_filter(glob('ipad/{*.jpg,*.png}', GLOB_BRACE), function ($file) {
$info = pathinfo($file);
return !preg_match('/#2x$/', $info['filename'])
&& !file_exists("$info[dirname]/$info[filename]#2x.$info[extension]");
}));

Categories