Loop throught directory and subdir - php

Pls sir, how can I loop through a directory and get the sub-directory name and all the files names so that I can generate a directory try, am trying to build a file manager in php.
I have tried:
$dir = new DirectoryIterator(dirname(FILE));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}

You can scan a directory and display the name of files in it using the PHP Code below
<?php
$dir = 'dir/';
$files = scandir($dir);
$totFiles = sizeof($files);
for($i=2;$i<$totFiles;$i++){
$name = explode(".",$files[$i]);
echo "
$name[0]
";
}
?>

Related

Open and read files in directory inside folder in PHP

Okay guys so I am a bit lost as to how to adjust my code. Up to now, I have my code to read any Json file in a directory, parse it and put it in a table - works great since I was only using 1 JSON file per table row.
What I need to do now is the following, each IP address I have gives me 3 JSON files now that are placed into a folder with the IP address as its name. In my main directory I will have many folder each with 3 JSON files in it.
I want to read each file in every folder, place the info I parse in a table and then move on to the next folder as a new row and do the same.
FOR REFERENCE::
Current file layout:
FOLDER-->JSON
-->JSON
-->JSON
New file layout:
FOLDER-->IPADDRESS-->JSONFILE1
-->JSONFILE2
-->JSONFILE3
-->IPADDRESS2-->JSONFILE1
--JSONFILE2
-->JSONFILE3
Current code for reading any JSON file in a directory:
$dir = "my dir";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
foreach(glob("*_name.json") as $filename) {
$data = file_get_contents($filename);
$testing = json_decode($data, true);
echo "<tr>";
echo "<td>{$filename }</td>";
foreach($testing[0] as $row) {
// code for parsing here ...
}
}
}
}
here you go using RecursiveIteratorIterator Class
function Get_Files()
{
$dir = "my_dir";
$init = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
$files = array();
foreach ($init as $file) {
if ($file->isDir()) {
continue;
}
$files[] = $file->getPathname();
}
return $files;
}
foreach (Get_Files() as $file) {
$data = file_get_contents($file);
$testing = json_decode($data, true);
echo "<tr>";
echo "<td>{$file}</td></tr>";
}
output:
my_dir\192.168.0.1\JSONFILE1.json
my_dir\192.168.0.1\JSONFILE2.json

php - listing folders and files in a directory

hi there i am using the following function to list all the files and folders in a directory.
<?php
function listFolderFiles($dir){
$ffs = scandir($dir);
foreach($ffs as $ff){
echo $ff . "<br/>";
}
}
?>
but the problem seems to be i'm getting all the folders in the directory alright but i'm also getting a . and a ... something like the one below.
.
..
direc
img
music
New Text Document.txt
and i am using the following function like: listFolderFiles('MyFolder');
what i want to do is get all the folders and files but not the . and the .., what have i done wrong and how can i get what i want. thanks!
Easy way to get rid of the dots that scandir() picks up in Linux environments:
<?php
$ffs = array_diff(scandir($dir), array('..', '.'));
?>
You can use glob quite easily, which puts the filenames into an array:
print_r(glob("*.*"));
example:
// directory name
$directory = "/";
// get in directory
$files = glob($directory . "*");
$d = 0; // init dir array count
$f = 0; // init file array count
// directories and files
foreach($files as $file) {
if(is_dir($file)) {
array($l['directory'][$d] = $file);
$d++;
} else {
array($l['file'][$f] = $file);
$f++;
}
}
print_r($l);
NOTE: scandir will also pick up hidden files such as .htaccess, etc. That is why the glob method should be considered instead, unless of course you want to show them.
This should do it!
<?php
function listFolderFiles($dir){
$ffs = scandir($dir);
foreach($ffs as &$ff){
if ($ff != '.' && $ff != '..') {
echo $ff . "<br/>";
}
}
}
?>

PHP Get all files but not in subdirectories

Im using this code:
$path = realpath('');
$i = 0;
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($objects as $name => $object){
and it gets all sub directories in the main directory, when I only want it to get in the current directory
How would I go about doing that?
You could make use of glob() instead.
<?php
chdir('yourcurrentdirectory');
foreach(glob("*.*") as $file)
{
echo $files."<br>";
}

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 script for generating links to folders

Need help for a php script / page for generating links to folders.
Have a homepage with photos that I upload using Lightroom – each album in a separate folder.
The structure is:
mysite.com
|--images
|--folder1
|--folder2
|--folder3
.
.
So I would like to end up with a dynamic index.php file that generates links to all the subfolders of “images” instead of the static index.html file I got in the root of mysite.com:
<html>
<body>
folder1
folder2
folder3
.
.
</body>
</html>
Thanx in advance
<?php
$files = scandir();
$dirs = array(); // contains all your images folder
foreach ($files as $file) {
if (is_dir($file)) {
$dirs[] = $file;
}
}
?>
use dirs array for dynamically generating links
Maybe something like this:
$dir = "mysite.com/images/";
$dh = opendir($dir);
while ($f = readdir($dh)) {
$fullpath = $dir."/".$f;
if ($f{0} == "." || !is_dir($fullpath)) continue;
echo "$f\n";
}
closedir($dh);
When I need everything (i.e., something/*), I prefer readdir() over glob() because of speed and less memory consumption (reading a directory file by file, instead of getting the whole thing in an array).
If I'm not mistaken, glob() does omit .*files and has no need for the $fullpath variable, so if you're after speed, you might want to do some testing.
Try something like this:
$contents = glob('mysite.com/images/*');
foreach ($contents as content) {
$path = explode('/', $content);
$folder = array_pop($path);
echo '' . $folder . '';
}
Or also this:
if ($handle = opendir('mysite.com/images/') {
while (false !== ($content = readdir($handle))) {
echo echo '' . $content . '';
}
closedir($handle);
}

Categories