I have a top folder named home and nested folders and files inside
I need to insert some data from files and folders into a table
The following (simplified) code works fine if I manually declare parent folder for each level separatelly, i.e. - home/lorem/, home/impsum/, home/ipsum/dolor/ etc
Is there a way to do this automatically for all nested files and folders ?
Actually, I need the path for each of them on each level
$folders = glob("home/*", GLOB_ONLYDIR);
foreach($folders as $el){
//$path = ??;
//do_something_with folder;
}
$files = glob("home/*.txt");
foreach($files as $el){
//$path = ??;
//do_something_with file;
}
PHP has the recursiveIterator suite of classes - of which the recursiveDirectoryIterator is the correct tool for the task at hand.
# Where to start the recursive scan
$dir=__DIR__;
# utility
function isDot( $dir ){
return basename( $dir )=='.' or basename( $dir )=='..';
}
# create new instances of both recursive Iterators
$dirItr=new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::KEY_AS_PATHNAME );
$recItr=new RecursiveIteratorIterator( $dirItr, RecursiveIteratorIterator::CHILD_FIRST );
foreach( $recItr as $obj => $info ) {
# directories
if( $info->isDir() && !isDot( $info->getPathname() ) ){
printf('> Folder=%s<br />',realpath( $info->getPathname() ) );
}
# files
if( $info->isFile() ){
printf('File=%s<br />',$info->getFileName() );
}
}
I would suggest you to use The Finder Component
use Symfony\Component\Finder\Finder;
$finder = new Finder();
// find all files in the home directory
$finder->files()->in('home/*');
// To output their path
foreach ($finder as $file) {
$path = $file->getRelativePathname();
}
Related
I've created custom elements for WPBakery. In the functions.php file, I currently have the following:
add_action( 'vc_before_init', 'vc_before_init_actions' );
function vc_before_init_actions() {
require_once('vc_elements/text-image/init.php' );
require_once('vc_elements/text/init.php' );
}
However, as I build more custom elements, that list will be huge. What I'm looking to do is load all files named init.php in each vc_elements subfolder.
This is my current folder structure:
vc_elements
text-image
init.php
text
init.php
What's the cleanest way to go about this?
You need to use RecursiveDirectoryIterator to scan the folder and get all files which are named as init.php. Below is the code you can use
add_action( 'vc_before_init', 'vc_before_init_actions' );
function vc_before_init_actions() {
$dir = '/full_path_to_vc_elements';
$files = getFiles($dir, 'init.php');
foreach( $files as $file) {
require_once( $file );
}
}
function getFiles($dir, $match) {
$return = array();
$iti = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($iti as $file){
if ($file->isDir()) {
continue;
}
if(strpos($file , $match) !== false){
$return[] = $file->getPathname();
}
}
return $return;
}
So in future if you add any init.php file inside the folder, it will automatically be picked by getFiles() and included using require.
What I'm looking to do is load all files named init.php in each
vc_elements subfolder.
Assuming you mean only immediate sub-directorys of "vc_elements" you can use GlobIterator with an "*" as a subdirectory wildcard:
$myInitFiles = new GlobIterator('/path/to/vc_elements/*/init.php');
foreach ($myInitFiles as $file) {
require_once( $myInitFiles->key() );
}
unset($myInitFiles); // release object memory for garbage collection
You can obviously convert this to a more general function if required.
Perhaps something like this would work, assuming that directory only contains sub-directories with the elements you need.
$dir = 'path/to/vc_elements';
// Scan directory for its contents and put in array. Remove possiblity of . or ..
$files = array_diff(scandir($dir), array('..', '.'));
foreach ($files as $file) {
$name = '/path/to/vc_elements/' . $file . '/init.php';
include $name;
}
Not sure what the file structor is for your theme but if you have a folder like inc or int make a file called vc-functions.php in that file do something like this.
add_action( 'vc_before_init', 'vc_before_init_actions' );
function vc_before_init_actions() {
require_once('vc_elements/text-image/init.php' );
require_once('vc_elements/text/init.php' );
}
Then in the functions.php
require get_template_directory() . '/inc/vc-functions.php';
I'm looping unto directories and each directory consist of multiple files that yet to be rename. Below is the code
<?php
$path = __DIR__.'/';
$files = array_diff(scandir($path), array('.', '..'));
foreach($files as $f ){
$files2 = array_diff(scandir($path.'/'.$f), array('.', '..'));
foreach( $files2 as $f2 ){
rename($path.'/'.$f.'/'.$f2, $path.'/'.$f.'/'.strtolower(str_replace(' ','_',$f2)));
echo 'success<br>';
}
}
above codes return an error of
The system cannot find the file specified. (code: 2)
in each directory, some of the files has the name that consist of special character(s) e.g. Velāyat-e Nūrestān.json.
Any ideas ?
Your code,in the actual state can't work because there are a lot of issues in it.I suggest to use native Directory Iterator to achieve this properly .
You can use:
$root=__DIR__.'/';
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root));//create a recursive directory iterator
$it->rewind();
while($it->valid())
{
if (
!$it->isDot()//if file basename not in ['.','..']
&&$it->isFile()//and is really a file and not a directory
)
{
rename(str_replace('/','\\',$it->getPathname()),str_replace('/','\\',$it->getPath().'\\'.mb_strtolower(str_replace(' ','_',$it->getBasename()))));//try to rename it
echo "success";
}
$it->next();
}
I need to load index.php file from each of the plugins' folders. There is the main folder "plugins" and inside there are, sub folders (plugins) e.g blog, members etc. Inside each plugin folder there is an index.php file which i need to load. How can i load the directory and search for these files. The plugin folders are not static and might change.
What i have tried
$dir_iterator = new RecursiveDirectoryIterator($this->plugin_dir);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
// could use CHILD_FIRST if you so wish
foreach ($iterator as $file) {
echo $file, "\n";
}
and..the glob function (which didn't help much
$list = glob('index.php', GLOB_BRACE);
foreach($list as $files){
echo $files;
}
print_r($list);
I used a double listing way..
private function loadPlugins(){
$dir = array_diff(scandir($this->plugin_dir), array('..', '.'));
foreach($dir as $ds){
$list = glob($this->plugin_dir.'/'.$ds.'/index.php', GLOB_BRACE);
foreach($list as $files){
require $files;
}
}
}
I'm using RecursiveDirectoryIterator to scan for all files and folders within a given root dir. This works fine, but I'd like to keep track of all of the unique directories in that list, so I'm not sure that RecursiveDirectoryIterator is the way to go.
I have a directory structure of
-a
->b
->c
-one
->two
->three
Here is my code:
<?php
function test($dir){
$in_dir = 'none';
$currdir = 'none';
$thisdir = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($thisdir, RecursiveIteratorIterator::SELF_FIRST);
foreach($files as $object){
//if this is a directory... find out which one it is.
if($object->isDir()){
//figure out if we have changed directories...
$currdir = realpath($object->getPath());
if(strpos($currdir, '.') == false){
$test = strcmp($currdir, $prevdir);
if($test){
echo "current dir changing: ", $currdir, "\n";
$prevdir = $currdir;
}
}
}
}
}
test('fold');
?>
What I get from that is the following:
current dir changing: /Users/<usr>/Desktop/test/fold
current dir changing: /Users/<usr>/Desktop/test/fold/a
current dir changing: /Users/<usr>/Desktop/test/fold/a/b
current dir changing: /Users/<usr>/Desktop/test/fold
current dir changing: /Users/<usr>/Desktop/test/fold/one
current dir changing: /Users/<usr>/Desktop/test/fold/one/two
...But I only want the unique directories.
It's perhaps the method of object comparison in the loop that returns duplicates, as the iterator moves up and down the directory tree as it parses through folders.
The following worked for me. I also use array_unique() confirm no dupes as a redundancy.
$dirArray = []; // the array to store dirs
$path = realpath('/some/folder/location');
$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
// loop through all objects and store names in dirArray[]
foreach($objects as $name => $object){
if ($object->isDir()) {
$dirArray[] = $name;
}
}
// make sure there are no dupes
$result = array_unique($dirArray);
// print array out
print_r($result);
I am currently trying to make a script that will find images with *.jpg / *.png extensions in directories and subdirectories.
If some picture with one of these extensions is found, then save it to an array with path, name, size, height and width.
So far I have this piece of code, which will find all files, but I don't know how to get only jpg / png images.
class ImageCheck {
public static function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output.
$dh = #opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces $file</strong><br />";
ImageCheck::getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
echo "$spaces $file<br />";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
}
I call this function in my template like this
ImageCheck::getDirectory($dir);
Save a lot of headache and just use PHP's built in recursive search with a regex expression:
<?php
$Directory = new RecursiveDirectoryIterator('path/to/project/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+(.jpe?g|.png)$/i', RecursiveRegexIterator::GET_MATCH);
?>
In case you are not familiar with working with objects, here is how to iterate the response:
<?php
foreach($Regex as $name => $Regex){
echo "$name\n";
}
?>