How to get image names from all sub directories? - php

I have used following php code to get all images names from relevant directory.
$dir = "images";
$images = scandir($dir);
$listImages=array();
foreach($images as $image){
$listImages=$image;
echo ($listImages) ."<br>";
}
This one works perfectly. But I want to get all images file names within all sub directories from relevant directory. Parent directory does not contain images and all the images contain in sub folders as folows.
Parent Dir
Sub Dir
image1
image2
Sub Dir2
image3
image4
How I go through the all sub folders and get the images names?

Try following. To get full directory path, merge with parent directory.
$path = 'images'; // '.' for current
foreach (new DirectoryIterator($path) as $file) {
if ($file->isDot()) continue;
if ($file->isDir()) {
$dir = $path.'/'. $file->getFilename();
$images = scandir($dir);
$listImages=array();
foreach($images as $image){
$listImages=$image;
echo ($listImages) ."<br>";
}
}
}

Utilizing recursion, you can make this quite easily. This function will indefinitely go through your directories until each directory is done searching. THIS WAS NOT TESTED.
$images = [];
function getImages(&$images, $directory) {
$files = scandir($directory); // you should get rid of . and .. too
foreach($files as $file) {
if(is_dir($file) {
getImages($images, $directory . '/' . $file);
} else {
array_push($images, $file); /// you may also check if it is indeed an image
}
}
}
getImages($images, 'images');

Related

php script to delete file names not matching a dynamic text file

I have created a text file (images.txt) located in /home/users/images.txt, the File contain names of jpeg files. for example:
1.jpeg
12.jpeg
33.jpeg
This file is updated regularly and new image filenames are added
I am looking for a php script that can help in reading the filenames from the .txt and deleting any files from /home/user/images/ directory that does not match the filenames in the .txt file
I have tried the below code and cant get it to work
$array = explode("\n", file_get_contents('/home/user/images.txt'));
$directory = "/home/user/images/";
$files = glob($directory . "*.*");
foreach($files as $file)
{
if (!in_array($file, $array)) {
unlink($directory . $file);
}
}
The names returned by glob() include the directory prefix, but the names in $array don't have them. You need to remove the prefix before searching, and you don't need to add it when calling unlink().
$array = file('/home/user/images.txt', FILE_IGNORE_NEW_LINES);
$directory = "/home/user/images/";
$files = glob($directory . "*.*");
foreach($files as $file)
{
if (!in_array(basename($file), $array)) {
unlink($file);
}
}

PHP > Scan folder/subfolder for images > generate array for every folder

I want to automate an image gallery, for that I need to first scan for images in my gallery folder. Second I need to separate folders in arrays. Example:
this is my code so far:
$path = '/public_html/images/gallery/';
$directory = new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($directory,RecursiveIteratorIterator::LEAVES_ONLY);
$extensions = array("jpg", "jpeg");
foreach ($iterator as $fileinfo) {
if (in_array($fileinfo->getExtension(), $extensions)) {
$files[] = $fileinfo->getPathname();
}
}
/** print_r ($files); */
echo '<ul>';
foreach($files as $p){
echo '<li>'.$p.'</li>';
}
echo '</ul>';
this outputs all my images from that folder with it's subfolder. What I don't really know is how to extract from $files array, x subarrays for each folder. Example:
$files = {folder1/1.jpg, folder1/2.jpg, folder1/3.jpg, folder2/1.jpg, folder2/2.jpg }
next i want to extract folders to arrayx to become:
$folder1 = {folder1/1.jpg, folder1/2.jpg, folder1/3.jpg}
$folder2 = {folder2/1.jpg, folder2/2.jpg}
From this I can process it to generate lightbox entries. Thank you!
You can try to make the array multidimensional by adding the folder name as key:
foreach ($iterator as $fileinfo) {
if (in_array($fileinfo->getExtension(), $extensions)) {
$files[$fileinfo->getPath()][] = $fileinfo->getPathname();
}
}
Now you should have the different files splitted in different arrays depending on their path:
$files["path1"][0] = file1;
$files["path1"][1] = file2;
$files["path2"][0] = file1;
$files["path2"][1] = file2;

Empty files in directory

I am trying to simply empty all the files in a directory, but I keep getting an error that the path in file_put_contents is a directory.
//empty the cache
$files = scandir('tmp/whazzup/cache/');
if($files!=false){
foreach($files as $file){
file_put_contents('tmp/whazzup/cache/'.$file, '');
}
}
PHP scandir returns an array of all files and directories. So you are getting an array with elements like . and .. and any other sub-directories.
What you should probably do in your foreach loop:
foreach ($files as $file) {
// ignore directories
if (is_dir($file)) {
continue;
}
// process files
file_put_contents(...);
}

Deleting ".part" files from folder with PHP

I'm using the following to delete all files from the specified directory.
$files = glob('path/to/temp/*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
It removes everything other than partially uploaded files eg : myfile.mp3.part
I've tried specifying .part in the file path just to see if I can force it that way :
$files = glob('path/to/temp/*.part');
But that doesn't work either.
Am I missing something here? Is there a different method for deleting non-active partial files?
$files = scandir('/path/to/temp');
foreach($files as $key => $file) {
if ( preg_match('/.*?\.part$/', $file) ) {
unlink($file);
}
}
I'm using something likes this to delete all files in a folder.
$dir = "/path/to/temp";
$files = scandir($dir);
foreach($files as $file){
$path = $dir."/".$file;
if(is_file($path)) unlink($path);
}

List with array only some formats files n folder and subdirectory php on Ubuntu Server

I need to list all files for example mp4 or avi in my folder /Files and relative subdirectories and after that insert into <a href={$filename}><\a> tag so I need a array i suppose.
I tried with find command but I receive a string and not a Array so I've to split the string and this isn't practical.
Any suggestion?
or use class RecursiveDirectoryIterator - For example :
$dir_iterator = new RecursiveDirectoryIterator(dirname(__FILE__));
$iterator = new RecursiveIteratorIterator($dir_iterator);
foreach ($iterator as $filename)
{
if (dirname($filename) != dirname(__FILE__))
{
if(is_file($filename)) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == 'mp4' )
{
print ''.basename($filename)."<br />";
}
}
}
}
<?php
$dir ="/Files";
$files = scandir($dir);
foreach($files as $file) {
$fullname = "/Files/" . $file;
echo '<a href='.$fullname.'>File</a>;
}
This should work for you.

Categories