How to read the files and directories inside the directory - php

Can any one please let me know how to read the directory and find what are the files and directories inside that directory.
I've tried with checking the directories by using the is_dir() function as follows
$main = "path to the directory";//Directory which is having some files and one directory
readDir($main);
function readDir($main) {
$dirHandle = opendir($main);
while ($file = readdir($dirHandle)) {
if ($file != "." && $file != "..") {
if (is_dir($file)) {
//nothing is coming here
}
}
}
}
But it is not checking the directories.
Thanks

The most easy way in PHP 5 is with RecursiveDirectoryIterator and RecursiveIteratorIterator:
$dir = '/path/to/dir';
$directoryIterator = new RecursiveDirectoryIterator($dir);
$iterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $path) {
if ($path->isDir()) {
// ...
}
}
You don't need to recurse by yourself as these fine iterators handle it by themselves.
For more information about these powerful iterators see the linked documentation articles.

You have to use full path to subdirectory:
if(is_dir($main.'/'.$file)) { ... }

Use scandir
Then parse the result and eliminate '.' and '..' and is_file()

$le_map_to_search = $main;
$data_to_use_maps[] = array();
$data_to_use_maps = read_dir($le_map_to_search, 'dir');
$aantal_mappen = count($data_to_use_maps);
$counter_mappen = 1;
while($counter_mappen < $aantal_mappen){
echo $data_to_use_maps[$counter_mappen];
$counter_mappen++;
}
$data_to_use_files[] = array();
$data_to_use_files = read_dir($le_map_to_search, 'files');
$aantal_bestanden = count($data_to_use_files);
$counter_files = 1;
while($counter_files < $aantal_files){
echo $data_to_use_files [$counter_files ];
$counter_files ++;
}

Look at the reference here:
http://php.net/manual/en/function.scandir.php

Try this
$handle = opendir($directory); //Open the directory
while (false !== ($file = readdir($handle))) {
$filepath = $directory.DS.$file; //Get all files/directories in the directory
}

Related

PHP random folder

Let's say I have the following directory tree
tmp
---cat
---dog
---mouse
My index.php is in the same directory as tmp folder. How would I use PHP to save a random folder name as a variable? I've tried the following code but it didn't work.
<?php
function listFolderFiles(){
$dir = './tmp';
$ffs = scandir($dir);
$randomFolder = '';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
$randomFolder = $randomFolder + $ff;
}
}
echo $randomFolder;
echo '</ol>';
}
listFolderFiles();
?>
Another solution can be the built in DirectoryIterator object for iterating through file systems. Just have a look at the following example.
$results = [];
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot() && $fileinfo->isDir()) {
$results[] = $fileinfo->getFilename();
}
}
The given code iterates through a given directory and gives back all directories included in the given directory except the dots.
By create, do you mean return/echo?
I don't think your function will produce a random folder. It will return the last folder.
function listFolderFiles(){
$dir = './tmp';
$Ignore = array('.','..'); // build an ignore array
$Results = array();
$ffs = scandir($dir);
foreach($ffs as $ff){
if(!in_array($ff,$Ignore) && is_dir("./tmp/".$ff)){ // if filename is folder and not in ignore array
$Results[] = $ff; // add filename to results
}
}
shuffle($Results); // shuffle/randomize the results
echo $Results[0];
}
listFolderFiles();

Renaming all files within different sub directories

I m trying to rename files to lowercase within a directory, however the problem I'm having is being able to scan the sub-directories for the files.
So in this case $app_dir is the main directory and the files I need to change exist within multiple sub-folders.
Heres my code so far:
$files = scandir($app_dir);
foreach($files as $key=>$name){
$oldName = $name;
$newName = strtolower($name);
rename("$app_dir/$oldName","$app_dir/$newName");
}
Thanks for your help.
If you are trying to lowercase all file names you can try this:
Using this filesystem:
Josh#laptop:~$ find josh
josh
josh/A
josh/B
josh/f1
josh/f2
josh/is
josh/is/awesome
josh/is/awesome/e
josh/is/awesome/t
Code:
<?php
$app_dir = 'josh';
$dir = new RecursiveDirectoryIterator($app_dir, FilesystemIterator::SKIP_DOTS);
$iter = new RecursiveIteratorIterator($dir);
foreach ($iter as $file) {
if ($file != strtolower($file)) {
rename($file, strtolower($file));
}
}
Results:
Josh#laptop:~$ find josh
josh
josh/a
josh/b
josh/f1
josh/f2
josh/is
josh/is/awesome
josh/is/awesome/e
josh/is/awesome/t
This code does not take into account uppercase letters in directories but that exercise is up to you.
You could do this with a recursive function.
function renameFiles($dir){
$files = scandir($dir);
foreach($files as $key=>$name){
if($name == '..' || $name == '.') continue;
if(is_dir("$dir/$name"))
renameFiles("$dir/$name");
else{
$oldName = $name;
$newName = strtolower($name);
rename("$dir/$oldName", "$dir/$newName");
}
}
}
This basically loops through a directory, if something is a file it renames it, if something is a directory it runs itself on that directory.
Try like that
public function renameFiles($dir)
{
$files = scandir($dir);
foreach ($files as $key => $name) {
if (is_dir("$dir/$name")) {
if ($name == '.' || $name == '..') {
continue;
}
$this->renameFiles("$dir/$name");
} else {
$oldName = $name;
$newName = strtoupper($name);
rename("$dir/$oldName", "$dir/$newName");
}
}
}

directoryIterator has wrong "starting point"

I have a recursive directory iterator looking like this:
function ReadFolderDirectory($dir,$listDir= array())
{
$listDir = array();
if($handler = opendir($dir))
{
while (($sub = readdir($handler)) !== FALSE)
{
if ($sub != "." && $sub != ".." && $sub != "Thumb.db")
{
if(is_file($dir."/".$sub))
{
$listDir[] = $sub;
}elseif(is_dir($dir."/".$sub))
{
$listDir[$sub] = ReadFolderDirectory($dir."/".$sub);
}
}
}
closedir($handler);
}
return $listDir;
}
And I use it like this
$path = dirname(__FILE__);
$path = $path.'/uploadedImages/';
$dir = new DirectoryIterator($path);
$filesArray = ReadFolderDirectory($dir);
echo json_encode($filesArray);
Now when I try to set the starting point of the directory iteration, as you see I have added /uploadedImages/ to the path, but it seems to disregard that.
No matter if that is there or not, it always starts from the same directory as the php file is in, thus including also the index.php, ._index,php, and listing of course the folder uploadedImages itself.
Any thoughts what I am missing?
There is an error in your code, you have just to remove this code line :
$dir = new DirectoryIterator($path);
Explanation
opendir(String $pathToDir) // expects a String, but you pass an Object as a parameter

Fill up an array IF statement

<?php
if ($handle = opendir('gallery3/var/thumbs/Captain-America/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";?><br/><?
echo rtrim($file, '.jpg');?><br/><?
$names[]=$file;
}
}
closedir($handle);
}
?>
I want to createa an array of the file names that are outputting and also the rtrim elements.
glob (coupled with array_map) may do a better job, but you can create an array, and add matches to it very simply:
$files = array(); // declare
...
$files[] = rtrim($file,'.jpg'); // adding entry
...
print_r($files); // debug output to see it
The glob example:
// with or without the array_map to basename()
$files = array_map('basename',glob('gallery3/var/thumbs/Captain-America/*'));
var_dump($files); // normal files
$files_rtrim = array_map(create_function('$f','return rtrim($f,".jpg");'),$files);
var_dump($files_rtrim); // rtrim version of same files

List content of directory (php)

I have a folder. I want to put every file in this folder into an array and afterwards I want to echo them all in an foreach loop.
What's the best way to do this?
Thanks!
Scandir is what you're looking for
http://php.net/manual/en/function.scandir.php
<?php
$dir = '/tmp';
$files1 = scandir($dir);
print_r($files1);
?>
Or use combination of opendir and readdir
http://php.net/manual/en/function.readdir.php
Doesn't get much easier than this
http://ca3.php.net/manual/en/function.scandir.php
Don't forget to filter out hidden and parent directories (they start with a dot) on linux.
An Alternative:
define('PATH', 'files/');
$filesArray = array();
$filesArray = glob(PATH . '*', GLOB_ONLYDIR);
This method allow you to specify/filter a by file type. E.G.,
define('PATH', 'files/');
define('FILE_TYPE', '.jpg');
$filesArray = array();
$filesArray = glob(PATH . '*' . FILE_TYPE, GLOB_ONLYDIR);
You can also get the FULL path name to the file by removing the parameter 'GLOB_ONLYDIR'
This works for files and folders in subfolders too. Return list of folders and list of files with their path.
$dir = __DIR__; //work only for this current dir
function listFolderContent($dir,$path=''){
$r = array();
$list = scandir($dir);
foreach ($list as $item) {
if($item!='.' && $item!='..'){
if(is_file($path.$item)){
$r['files'][] = $path.$item;
}elseif(is_dir($path.$item)){
$r['folders'][] = $path.$item;
$sub = listFolderContent($path.$item,$path.$item.'/');
if(isset($sub['files']) && count($sub['files'])>0)
$r['files'] = isset ($r['files'])?array_merge ($r['files'], $sub['files']):$sub['files'];
if(isset($sub['folders']) && count($sub['folders'])>0)
$r['folders'] = array_merge ($r['folders'], $sub['folders']);
}
}
}
return $r;
}
$list = listFolderContent($dir);
var_dump($list['files']);
var_dump($list['folders']);
Edit: dwich answer is better. I will leave this just for information.
readdir.
<?php
if ($handle = opendir('/path/to/dir')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
closedir($handle);
}
?>
Hope this helps.
—Alberto

Categories