Foreach glob to include files in a subdirectory - php

I'm trying to learn how to include all the files in a directory using glob(), however I can't seem to get it to work. This is the code I have now:
foreach (glob("addons/*.php") as $filename) {
include $filename;
}
However a single file include seems to work just fine:
include "addons/hello.php";
This is what my file structure looks like:
Theme
-addons
--hello.php
-index.php
-options.php
So I'm not sure where the problem is. The code is inside a (theme) subdirectory itself, if that makes a difference at all. Thanks.

Use this for testing:
foreach (glob("addons/*.php", GLOB_NOCHECK) as $filename) {
PRINT $filename . "\n";
}
Should the directory not exist relatively to the current, then it will show addons/*.php as output.

This recursive function should do the trick:
function recursiveGlob($dir, $ext) {
$globFiles = glob("$dir/*.$ext");
$globDirs = glob("$dir/*", GLOB_ONLYDIR);
foreach ($globDirs as $dir) {
recursiveGlob($dir, $ext);
}
foreach ($globFiles as $file) {
include $file;
}
}
Usage: recursiveGlob('C:\Some\Dir', 'php');
If you want it to do other things to the individual file, just replace the include $file part.

Include is going to be using the search path which (while it typically includes the current working directory) isn't limited to that... using glob() with a relative directory path will always be relative to the current working directory. Before you enter your loop... ensure that your current working directory is where you think it is using echo getcwd()... you may find you're not in the Theme subdirectory after all; but that the Theme subdirectory is in the search path.

Make sure that path to file is absolute (from root of your server).
In my case this example works without problems:
$dir = getcwd();//can be replaced with your local path
foreach (glob("{$dir}/addons/*.php") as $filename) {
if(file_exists($filename))
{
//file exists, we can include it
include $filename;
}
else
{
echo 'File ' . $filename . ' not found<br />';
}
};

Related

Delete folder and files in PHP

I have a question about the little code snippet below.
At the moment I use the first code snippet and it runs perfectly.
But wouldn't the second code be a better way to delete the folder and files in it?
My variable $target is everytime a path to the folder hwo needs to delete.
function deleteFilesAndDirectory($target)
{
if(is_dir($target))
{
$files = glob($target . '*', GLOB_MARK);
foreach($files as $file)
{
deleteFilesAndDirectory($file);
}
rmdir($target);
}
elseif(is_file($target))
{
unlink($target);
}
}
Why this code shouldn't be used?
function deleteFilesAndDirectory($target)
{
$files = glob($target . '*', GLOB_MARK);
foreach($files as $file)
{
unlink($file);
}
rmdir($target);
}
The second will work fine, so long as the directory to be deleted does not contain any subdirectories. To clean out subdirectories, a recursive function is the best way, which is why in the first code sample the function deleteFilesAndDirectory() calls itself.

PHP glob function from another directory

I have some PDF files in public_html/site.com/pdf but in my index files is located in public_html/site.com/
I would like to use the glob() function to iterate through all the pdf files located In the pdf/ folder. The problem is that I am not getting any result.
Here is that I tried.
# public_html/index.php
<?php
foreach (glob("pdf/*.pdf") as $filename) {
echo "$filename <br/>";
}
?>
Alternatively, if you want to search your public folder recursively, you can use RecursiveDirectoryIterator to achieve this: Consider this example:
Lets say you have this directory structure:
/var/
/www/
/test/
/images/
image.png
/files/
/files2/
pdf.pdf <-- searching for some pdf files, happens to be here
<?php
$filetype_to_search = 'pdf';
$root_path = '/var/www/test'; // your doc root (or maybe C:/xampp/htdocs/) :p
foreach ($iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root_path,
RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST) as $value) {
if($value->getExtension() == $filetype_to_search) {
echo $value->getPathname() . "<br/>";
}
}
// ouput should be /var/www/test/images/files/files2/pdf.pdf
?>
My advice? Just set your full path as a variable & use it in cases like this.
In general you really cannot trust automatic methods used to get paths to be reliable for various reasons. This is why I have decided it’s best to set a base path explicitly as I explain here. I will assume you are on a standard Linux setup with /var/www/ as the root. So in your case you would set:
$BASE_PATH = '/var/www/public_html/site.com/';
And then your final code would be something like this:
$BASE_PATH = '/var/www/public_html/site.com/'
foreach (glob($BASE_PATH . "pdf/*.pdf") as $filename) {
echo "$filename <br/>";
}

Find path to file on server using php -

I would like to know how to get the absolute file path of the file i have found using glob() function. I am able to find a desired file using
foreach (glob("access.php") as $filename) {
echo "$filename absolutepath is: ";
}
not sure what function gets the full path of the file searched. Tried to google but can't find anything sensible.
Thanks
Slight update :
I have noticed that glob() function only searches the directory that the script is run from - and that is not good to me. I need a function that is equivalent to unix find / -name "somename"
Any alternative ? or am i missing something with the glob() ??
If you have to look also for files in subdirectories, you could use something like the following:
foreach (glob("{access.php,{*/,*/*/,*/*/*/}access.php}", GLOB_BRACE) as $filename) {
echo "$filename absolutepath is: ".realpath($filename);
}
You can use realpath to get file absolute path. More info: http://www.php.net/manual/en/function.realpath.php
I thinkt you need realpath(), as described here: http://www.php.net/manual/en/function.realpath.php
foreach (glob("access.php") as $filename) {
echo "$filename absolutepath is: " . realpath($filename);
}
The directory in which the glob function searches is available through the getcwd function.
To search any directory, given its path, one may use the following code snippet:
$dirToList = '/home/username/documents';
$patternToSearch = '*.odt'; // e.g. search for LibreOffice OpenDocument files
$foundFiles = FALSE;
$olddir = getcwd();
if (chdir($dirToList)) {
$foundFiles = glob($patternToSearch);
chdir($olddir); // switch back to the dir the code was running in before
if ($foundFiles) {
foreach ($foundFiles as $filename) {
echo nl2br(htmlentities(
'found file: '.$dirToList.DIRECTORY_SEPARATOR.$filename."\n"
, ENT_COMPAT, 'UTF-8'));
}
}
// else echo 'no found files';
}
// else echo 'chdir error';
To finally satiesfy your wish to do a search like
find / -name "somename"
you may put that code snippet in a function and call it while iterating through the directory tree of interest using PHP's RecursiveDirectoryIterator class.

PHP - Deleting folder/files only if there are no more in there

$value can = a folder structure to the language file. Example: languages/english.php
$value can also = the files name. Example: english.php
So I need to get the current folder that $value is in and delete the folder ONLY if there are no other files/folders within that directory (after deleting the actual file as I am doing already, ofcourse).
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
#unlink($module_path . '/' . $value);
// Now I need to delete the folder ONLY if there are no other directories inside the folder where it is currently at.
// And ONLY if there are NO OTHER files within that folder also.
}
}
How can I do this?? And wondering if this can be done without using a while loop, since a while loop within a foreach loop could take some time, and need this to be as quick as possible.
And just FYI, the $module_path should never be deleted. So if $value = english.php, it should never delete the $module_path. Ofcourse, there will always be another file in there, so checking for this is not necessary, but won't hurt either way.
Thanks guys :)
EDIT
Ok, now I'm using this code here and it is NOT working, it is not removing the folders or the files, and I don't get any errors either... so not sure what the problem is here:
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
if (#unlink($module_path . '/' . $value))
#rmdir(dirname($module_path . '/' . $value));
}
}
NEVERMIND, this works a CHARM!!! Cheers Everyone!!
The easyest way is try to use rmdir. This don't delete folder if it is not empty
rmdir($module_path);
also you can check is folder empty by
if(count(glob($module_path.'*'))<3)//delete
2 for . and ..
UPD: as I reviewed maybe you should replace $module_path by dirname($module_path.'.'.$value);
Since the directory you care about might be part of the $value, you need to use dirname to figure out what the parent directory is, you can't just assume that it's $module_path.
$file_path = $module_path . '/' . $value;
if (#unlink($file_path)) {
#rmdir(dirname($file_path));
}
if (is_file($value)) {
unlink($value);
} else if (is_dir($value)) {
if (count(scandir($value)) == 2) }
unlink($value)
}
}
http://php.net/manual/en/function.is-dir.php
http://www.php.net/manual/en/function.scandir.php
The code below will take a path, check if it is a file (i.e. not a directory). If it is a file, it will extract the directory name, then delete the file, then iterate over the dir and count the files in it, if the files are zero it'll delete the dir.
Code is as an example and should work, however privileges and environment setup may result in it not working.
<?php
if(!is_dir ( string $filename )){ //if it is a file
$fileDir = dirname ( $filename );
if ($handle = opendir($fileDir)) {
echo "Directory handle: $handle\n";
echo "Files:\n";
$numFiles=0;
//delete the file
unlink($myFile);
//Loop the dir and count the file in it
while (false !== ($file = readdir($handle))) {
$numFiles = $numFiles + 1;
}
if($numFiles == 0) {
//delete the dir
rmdir($fileDir);
}
closedir($handle);
}
}
?>

I need to find a file in directory and copy it to a different directory

I merely have the file name, without extension (.txt, .eps, etc.)
The directory has several subfolders. So, the file could be anywhere.
How can I seek the filename, without the extension, and copy it to different directory?
http://www.pgregg.com/projects/php/preg_find/preg_find.php.txt seems to be exactly what you need, to find the file. then just use the normal php copy() command http://php.net/manual/en/function.copy.php to copy it.
https://stackoverflow.com/search?q=php+recursive+file
have a look at this http://php.net/manual/en/function.copy.php
as for seeking filenames, could use a database to log where the files are? and use that log to find your files
I found that scandir() is the fastest method for such operations:
function findRecursive($folder, $file) {
foreach (scandir($folder) as $filename) {
$path = $folder . '/' . $filename;
# $filename starts with desired string
if (strpos($filename, $file) === 0) {
return $path;
}
# search sub-directories
if (is_dir($path)) {
$result = findRecursive($path);
if ($result !== NULL) {
return $result;
}
}
}
}
For copying the file, you can use copy():
copy(findRecursive($folder, $partOfFilename), $targetFile);

Categories