Scan folder for folders, and get first image of folder - php

I've got multiple folders within a folder. I'm trying to make a type of gallery.
I want to scan the first folder (FolderA) for all the folders within it.
Next thing I want to do is get the first picture of that folder, ignoring everything that is not a image.
It need's to be a preview of the first image in each folder.

RecursiveDirectoryIterator can help for you to iterate a directory tree.
$path = '/path/to/FolderA';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$firsts = array();
foreach($iterator as $name => $item){
if (!$item->isDir()) {
if (!isset($firsts[$item->getPath()]) && exif_imagetype($item->getRealPath())) {
$firsts[$item->getPath()] = $item->getRealPath();
}
}
}
var_dump($firsts);

I've done some extra research and the following worked for me:
foreach(glob('cms/images/realisaties/*', GLOB_ONLYDIR) as $dir) {
$dirname = basename($dir);
$mappen[] = $dirname;
}
foreach($mappen as $map){
$search_dir = "cms/images/realisaties/".$map;
$images = glob("$search_dir/*");
sort($images);
if (count($images) > 0) {
$img = $images[0];
echo '
<!--product item-->
<div class="product_item hit w_xs_full">
<figure class="r_corners photoframe type_2 t_align_c tr_all_hover shadow relative">
<!--product preview-->
<a href="realisaties/40-realisaties/'.$map.'" class="d_block relative wrapper pp_wrap m_bottom_15" >
<img src="'.$img.'" class="tr_all_hover" alt="0" style="max-height:242px">
</a>
<!--description and price of product-->
<figcaption>
<h5 class="m_bottom_10">'.ucfirst($map).'</h5>
<button class="button_type_12 bg_scheme_color r_corners tr_all_hover color_light mw_0 m_bottom_15">Bekijk</button>
</figcaption>
</figure>
</div>
';
} else {
// possibly display a placeholder image?
}
}
}
The folder containing the folders that had the images is "realisaties". With GLOB I first went through them. After that I put all the folder names in an array.
With that array I made another loop. I used glob again to look what is inside that folder. After that I sorted the images, and set the preview image to be the last added.

Related

how to show files from directory and all subdirectories?

I'm working on my photo gallery when user can upload photos and also choose a category. My categories are subdirectories in images/. When user doesn't choose a category then photos are stored in images/. I want to display all photos (from all categories and other) in gallery but now I manage to show only these without category. Can someone help me?
Here's fragment of my php code
$fo=opendir("images");
if ($dh = opendir("images")){
$count = 1;
while($file=readdir($fo)){
if($file!="" && $file!="." && $file!=".."){
$image_path = "images/".$file;
if(!is_dir($image_path)){
?>
<div class="gallery">
<a href="<?= $image_path; ?>">
<img src="<?= $image_path; ?>">
I tried to list all subdirectories
$directories = glob("images" . '/*' , GLOB_ONLYDIR);
but I don't know what to do next
You should use a RecursiveDirectoryIterator, see https://www.php.net/manual/en/class.recursivedirectoryiterator.php
You could then do something like:
$folder = "path to your folder";
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $fileinfo) {
// fileinfo is an object, see documentation for info
$path = $fileinfo->getRealPath();
}

Foreach txt and image files with different code blocks

I have a gallery. I would like to glob files into. It works fine for jpg, png etc.
Directory:
1.jpg
2.png
3.jpg
...
Code :
foreach ($gallery as $u)
{
echo'<div class="section active" id="">';
foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {
echo '<div class="slide"><img class="" src="https://onlinegallery.online/'.$filename.'" /></div>'; //slide
}
echo('</div>');
}
I would like to put a txt file to directory and create foreach for txt and image files (Some slides should be a txt files). I don't know how to do that because txt file can't be used in img src tag. It should looks something like this.
Directory:
1.png
2.img
3.txt
4.jpg
$images = '<img class="" src="https://onlinegallery.online/'.$filename.'" />';
$txt = '<div><p>fopen("'.$filename.'", "r");
echo fread($txt,filesize("'.$filename.'"));
fclose($txt); </p></div>';
foreach ($gallery as $u)
{
echo'<div class="section active" id="">';
foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {
echo '<div class="slide">
//$images or $txt files
//i need txt and images files here
</div>'; //slide
}
echo('</div>');
}
I suppose I'm completely out, but thank you for your advice anyway.
You'll need to read the contents of your text files and output them. Be careful to sanitize the text contents - you don't want to accidentally emit something that's treated as html, especially if the contents are coming from an unknown source (read more).
You'll also need to add an if inside the for loop to determine if you're outputting an image or text. For images, you can keep using your existing code.
For text, something like this might work:
echo htmlentities(file_get_contents($filepath));
foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {
$imgFileType = pathinfo($filename,PATHINFO_EXTENSION);
$title = basename("$meno/$new/$filename", ".jpg").PHP_EOL;
if(($imgFileType == 'jpg') || ($imgFileType == 'png') || ($imgFileType == 'jpeg') || ($imgFileType == 'gif')) {
echo '<div class="slide"><img class="" onclick="fullscreen()" src="https://onlinegallery.online/'.$filename.'" alt="'.$title.'"/><p class="imagetitle">'.$title.'</p></div>';
}
if(($imgFileType == 'txt')) {
echo '<div class="slide"><p class="txtslide" onclick="fullscreen()">';
echo filter_var(file_get_contents($filename), FILTER_SANITIZE_STRING);
echo '</p><p class="imagetitle">'.$title.'</p></div>';
}
}
echo('</div>');

Display images from folder

I have been making a blog, but I have a problem. I can't display image from folders images. I need to display one image every time when name and comment put on the page. Every time another image and need to stay on page.
Here is link
http://slimhamdi.net/lina/demos/blog-post-dark.html?name=hhhhhhh&email=hh%40hotmail.com&comment=h&send=
I need same like this blog, I would like to avoid MySQL. Any help will be appreciated.
<?php
$images = array("user1.jpg", "user2.jpg", "user1.jpg");
$images = glob('images/*');
shuffle($images );
foreach($images as $image ) {
break;
}
?>
<img src="<?php echo "$image"; ?>" />
You are overwriting variables:
<?php
$images = array("user1.jpg", "user2.jpg", "user1.jpg");
$images = glob('images/*'); // Overwrites the previous $images
That way the $images in the foreach is something else.
There is also no need to use a break in the foreach loop
<?php
$images = array("user1.jpg", "user2.jpg", "user1.jpg");
shuffle($images );
foreach($images as $image ) {
echo '<img src="'.$image.'" />';
//echo '<img src="images/'.$image.'">';// With file path
}
why do you use break in foreach?
you should echo the img tag in foreach
if your images are in images folder, you shouldn't you glob, and instead you can concat it to path.
<?php
$images = array("user1.jpg", "user2.jpg", "user1.jpg");
shuffle($images);
foreach($images as $image ) {
echo "<img src='images/{$image}' />";
}
?>

PHP recursively find files and folders and create HTML

Basically what I am trying to do is take a base directory (already defined) and recursively go down it, making a link in a navbar for files and a collapsible for directories; under the collapsible would be links for files in that directory and possibly more collapsibles for directories inside the directory. Here is what I have so far, which is not working:
foreach (new DirectoryIterator($dir) as $file) {
if ($file->isDot()) continue;
if ($file->isFile()) {
echo "<li>" . $file . "</li>"; /*This successfully
creates links named from all the files in the directory specified by $dir */
}
if ($file->isDir()) {
?>
<li class="no-padding">
<ul class="collapsible collapsible-accordion">
<li>
<a class="collapsible-header"><?php echo $file->getFilename(); ?></a>
<div class="collapsible-body">
<ul>
<?php
$dir2 = $file->getFilename();
foreach (new DirectoryIterator($dir."/".$dir2) as $file1) {
if ($file1->isDot()) continue;
if ($file1->isFile()) {
echo "<li>".$file1 . "</li>"; }
} ?>
</ul>
</div>
</li>
</ul>
</li>
<?php
}
}
?>
However, for some reason it seems a DirectoryIterator within a DirectoryIterator is no good (the $dir2 was for test purposes). Or I could have a syntax issue. The reason I want this to work this way is because I want the files to be contained in <li>file</li> html and the files under a directory to be in <li>file-in-folder</li> format.
If there is a better way to do this, please let me know! Thanks!
EDIT: I changed $1file to $file1 and it works fine, even appended the dir; however, I basically want something like a for loop that will keep creating the collapsibles within each other if there is still a directory present. Basically so it would automatically create the formatting if I had:
Dir1 (main) >
File 1 //link
File 2 //link
Dir 1 > //collapsible header
File 1.1 //collapsible button
File 1.2 //...
Dir 2 >
File 2.1
File 2.2
Dir 3
Without me having to write 10 nested DirectoryIterators, just in case you can go down that far.
I think you are using an invalid variable name. PHP accepts variables starting with letters and underscore followed by other chars. Try $file1 instead of $1file
Cheers!
http://php.net/manual/en/language.variables.basics.php
This is my logic, probably you can get some idea from here.
if your main folder looks like this
then here is the code to get the folder structures.
echo '<pre>';
$dir='folders';
$files = array_slice(scandir($dir), 2);
foreach($files as $k=>$file){
$dir1=$dir.'/'.$file;
if(is_dir($dir1)){
$files1 = array_slice(scandir($dir1), 2);
if(!$files1){
$FOLDERS[$file]=$file;
}else{
foreach($files1 as $kk=>$file1){
$dir2=$dir1.'/'.$file1;
$files2 = array_slice(scandir($dir2), 2);
if(!$files2){
$FOLDERS[$file][$file1]=$file1;
}else{
foreach($files2 as $file2){
$FOLDERS[$file][$file1][$file2]=$file2;
}
}
}
}
}
}
print_r($FOLDERS);
Output:
Array
(
[folder1] => folder1
[folder2] => Array
(
[folder3] => Array
(
[folder4] => folder4
)
[folder5] => folder5
[folder6] => folder6
)
)
i used it only to scan the folders, you can extend it according to your needs.

I get a broken image icon for the output

I know it's accessing the directory because the correct number of broken icons are there. Even alt='Image not there' doesn't work, it only widens the element its in but doesn't show any text. I tried other scripts where it displayed the alt='Image not there' but still gave a broken image icon. I also tried to simply echo an image from the folder and still got a broken image icon so what am I doing wrong? Is it even a script thing or what is going on?
<?php
$dirname = "C:/uploads/";
$images = scandir($dirname);
shuffle($images);
$ignore = Array(".", "..");
foreach ($images as $curimg) {
if (!in_array($curimg, $ignore)) {
echo "<li><a href='".$dirname.$curimg."'>
<img src='img.php?src=".$dirname.$curimg."&w=300&zc=1' alt='Image not working' /></a></li>\n ";
}
}
?>
You should provide an URL and not a local path here:
echo "<li><a href='".$dirname.$curimg."'>
<img src='img.php?src=".$dirname.$curimg."&w=300&zc=1' alt='Image not working' /></a>
$dirname is not accessable to the outside world and should be something like:
www.my.domain.com/uploads/
You need to create a folder into your (if you are working in local machine)local server site folder. Because PHP is a server side scripting language. So only the files move into your folder correctly. then you can simply call
<?php
$dirname = "uploads/";
$images = scandir($dirname);
shuffle($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
echo "<li><a href='".$dirname.$curimg."'>
<img src='img.php?src=".$dirname.$curimg."&w=300&zc=1' alt='Image not working' /></a></li>\n ";
}
}
?>
if you call images from local machine its not a logic. because you are building website. this website not show only your system. it shows all system. also all systems are not contain a uploads folder.

Categories