I want to include every file from every directory in my project. What I currently have is, that I include every file from a specific directory
foreach (glob("*.php") as $filename)
{
include_once $filename;
}
But I also want to do the same for every directory I have and all the files in there. I heard of the __autoload function, but I also need it sometimes in for non-class-functions.
On this man page, the first comment gives a function that lists all the files recursively. Just adapt it to match your needs:
<?php
function include_all_php_files($dir)
{
$root = scandir($dir);
foreach($root as $value)
{
if($value === '.' || $value === '..') {continue;}
if(is_file("$dir/$value") && preg_match('#\.php$#', $value))
{
include_once ("$dir/$value");
continue;
}
include_all_php_files("$dir/$value");
}
}
?>
Recursion is your friend.
/**
* #param string path to the root directory
*/
function include_files($dir) {
foreach (glob($dir . "/*") as $file) {
if(is_dir($file)){
include_files($file);
} else {
include_once($file);
}
}
}
Try this. This works for me.
$accepted_extension = array("jpeg", "jpg", "gif", "bmp", "png");
$return = array();
$results = scandir($folder);
foreach ($results as $result) {
if ($result == '.' or $result == '..')
continue;
else if (is_dir($folder . '/' . $result))
continue;
else {
$extn = substr($result, strpos($result, ".") + 1);
if (in_array($extn, $accepted_extension)) {
$return[] = $result;
}
}
}
Related
I've tried several ways to include a PDF file using PHP on Linux, it works normally on Windows, but not on Linux.
I have several directories with accents and I need to include PDF files that are inside the directories.
I pass the name of the PDF files and include the PDF.
My problem is with the encoding and accentuation of the folders. The files doesn't have accents, only the folders.
Examples of folders / files:
files/ño/hash1.pdf
files/nó/hash2.pdf
files/ção/hash.pdf
function getFileInContents($dir, $filename)
{
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir . '/' . $value);
if (!is_dir($path)) {
if ($filename == $value) {
return $path;
}
} elseif ($value != "." && $value != "..") {
getFileInContents($path, $filename);
}
}
return null;
}
if (!isset($_GET['f'])) {
echo 'File not found';
exit;
}
$local = 'files/';
$path = getFileInContents($local, $_GET['f']);
if (!$path) {
echo 'File not found';
exit;
}
$mime = mime_content_type($path);
header('Content-Type: ' . $mime);
include_once($path);
My answer adds on and expounds on the one offered up by #James, because you have additional issues:
As pointed out in the comment made by #Olivier, you should be using readfile() instead of include.
You should not include the final '/' in your declaration of $local since you will be concatenating a '/' to the passed $dir argument in function getFileInContents.
Presumably function getFileInContents is intended to recursively search subdirectories, but it is not doing this correctly; it only is searching the first subdirectory it finds and if the sought file is not present in that subdirectory it returns with a "not found" condition and never searches any other subdirectories that might be present in the directory.
function getFileInContents($dir, $filename)
{
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir . '/' . $value);
if (!is_dir($path)) {
if ($filename == $value) {
return $path;
}
} elseif ($value != "." && $value != "..") {
$new_path = getFileInContents($path, $filename);
if ($new_path) {
return $new_path;
}
}
}
return null;
}
if (!isset($_GET['f'])) {
echo 'File not found';
exit;
}
$local = 'files';
$path = getFileInContents($local, $_GET['f']);
if (!$path) {
echo 'File not found';
exit;
}
$mime = mime_content_type($path);
header('Content-Type: ' . $mime);
readfile($path);
I don't think the problem is anything to do with the folder names. I think the problem is that your recursive function is not actually returning the value when it finds the file.
When you call getFileInContents($path, $filename); you then need to return the value, if it's not null, to break the loop.
function getFileInContents($dir, $filename)
{
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir . '/' . $value);
if (!is_dir($path)) {
if ($filename == $value) {
return $path;
}
} elseif ($value != "." && $value != "..") {
$testValue = getFileInContents($path, $filename);
if ($testValue!=null){
return $testValue;
}
}
}
return null;
}
I took over this site for management. the former developer used opendir() which opens only one level before getting the files in the folder. I would like to create multi-level folders before the final files. I created the sub-folders on the server but I need to modify the code to dynamically recognise the sub-folders as folders not file.
if ($handle = opendir("parentfolder/".$pageid.'/')) {
$list = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$list[] = "$file\n";
}
}
rsort($list);
$clength = count($list);
for($x = 0; $x <$clength; $x++){
$pubFolders .= "<a href='".$maindomain."/reports/".$list[$x]."' class='imagefolders'><img src='".$maindomain."/images/icons/image.png' alt=''/><br>".$list[$x]."</a>";
}
$data = $data.$pubFolders;
closedir($handle);
}
Use glob() with GLOB_ONLYDIR; some example functions are as follows:
function findDirectories($rootPath) {
$directories = array();
foreach (glob($rootPath . "/*", GLOB_ONLYDIR) as $directory) {
$directories[] = $directory;
}
return $directories;
}
function findFiles($rootPath, $extension) {
$files = array();
foreach (glob($rootPath . "/*.$extension") as $file) {
$files[] = $file;
}
return $files;
}
function findFilesRecursive($rootPath,$extension) {
$files = findFiles($rootPath,$extension);
$directories = findDirectories($rootPath);
if (!empty($directories)) {
foreach ($directories as $key=>$directory) {
$foundFiles = findFilesRecursive($directory,$extension);
foreach ($foundFiles as $foundFile) {
$files[] = $foundFile;
}
}
}
return $files;
}
If you don't care about defining specific extensions, just pass in * as the $extension parameter.
hi all I have made a function
function getDirContents($dir, &$results = array()){
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
$results[] = $path;
} else if(is_dir($path) && $value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
and I am calling it in like
$value = $this->getDirContents("/var/www/staging/public/files/rgerger");
way from my controller by I am uable to get the full details of the folder I mean the directories and the subdirectories with all contents ..
scandir is on only giving the folder under the target folder which is only scaned but this is not giving me the content of the child folder upto the end.
You need to assign the result of the recursive method call back to the caller.
My (untested) example
function getDirectoryContents($dir)
{
$files = [];
if (is_dir($dir)) {
foreach(scandir($dir) as $key => $fileName) {
$filePath = realpath($dir . DIRECTORY_SEPARATOR . $fileName);
if ($fileName == '.' || $fileName == '..') {
continue;
}
if (is_dir($filePath)) {
$files[] = getDirectoryContents($filePath);
} else {
$files[] = $fileName;
}
}
}
return $files;
}
As per my comment, you can also use the SPL RecursiveDirectoryIterator which is PHP's inbuilt OOP solution for iterating the file system.
i want to list all directory, sub-directory and files using php.
i have tried following code. it returns all the directory, sub directory and files but it's not showing in correct order.
for ex:default order is 1dir, 2dir, 7dir, 8dir while in browser it shows 1dir, 8dir, 7dir, 2dir which is not correct.
code:
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..') {
printSubDir($file, $path);
}
else if ($file != '.' && $file !='..'){
$allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
$queue[] = $file;
}
}
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
sort($queue);
foreach ($queue as $file)
{
//printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li><a href=\"".$path.$file."\" target='_blank'>$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir($path);
?>
need help to fix the code and display the direcotry , subdirectory and files in correct order.
I'm having the same problem during listing a directory files. But I have used DirectoryLister
This code is very useful. You can list out your files easily.
You can implement it by following steps.
Download and extract Directory Lister
Copy resources/default.config.php to resources/config.php
Upload index.php and the resources folder to the folder you want listed
Upload additional files to the same directory as index.php
I hope this might help you
You can start by looping the array and printing each directory:
public function dirtree($dir, $regex='', $ignoreEmpty=false) {
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
// print_r($node);
$tree = dirtree($node->getPathname(), $ignoreEmpty);
// print"<pre>";print_r($tree);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
//if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
asort($dirs);
sort($files);
return array_merge($files, $dirs);
}
Use like this:
$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);
I was looking at RecursiveDirectoryIterator and glob to say
"return me a list of files (in an array) based on the extension (for example) .less. Oh and look in all child, grandchild and so on and so forth, excluding . and .. until you find all files matching."
But I am not sure the best approach to create a recursive function that keeps going well beyond the grand child.
What I have is a mess, its worked for two years - but now I need to refactor and change it up:
public function get_directory_of_files($path, $filename, $extension) {
if (!is_dir($path)) {
throw new AisisCore_FileHandling_FileException("Could not find said path: " . $path);
}
if (file_exists($filename)) {
$handler = opendir($path);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$this->package_files [] = $file;
$count = count($this->package_files);
for ($i = 0; $i < $count; $i++) {
if (substr(strrchr($this->package_files [$i], '.'), 1) == $extension) {
if ($this->package_files [$i] == $filename) {
$this->files_got_back = $this->package_files [$i];
}
}
}
}
}
}
return $this->_files_got_back;
}
This requires a file name to be passed in and thats not really my thing to do any more. So how can I re-write this function to do the above "pseudo code"
This function recursively finds files with a matching ending string
function getDirectoryContents($directory, $extension)
{
$extension = strtolower($extension);
$files = array();
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid())
{
if (!$it->isDot() && endsWith(strtolower($it->key()), $extension))
{
array_push($files, $it->key());
}
$it->next();
}
return $files;
}
function endsWith($haystack, $needle)
{
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
Used like so
print_r(getDirectoryContents('folder/', '.php'));
It converts the extension to lowercase to compare against
Take a look at this code:
<?php
class ex{
private function get_files_array($path,$ext, &$results){ //&to ensure it's a reference... but in php obj are passed by ref.
if (!is_dir($path)) {
//throw new AisisCore_FileHandling_FileException("Could not find said path: " . $path);
}
if ($dir = opendir($path)) {
$extLength = strlen($ext);
while (false !== ($file = readdir($dir))) {
if ($file != '.' && $file != '..'){
if (is_file($path.'/'.$file) && substr($file,-$extLength) == $ext){
$results[] = $path . '/' . $file; //it's a file and the correct extension
}
elseif (is_dir($path . '/'. $file)){
$this->get_files_array($path.'/'.$file, $ext, $results); //it's a dir
}
}
}
}else{
//unable to open dir
}
}
public function get_files_deep($path,$ext){
$results = array();
$this->get_files_array($path,$ext,$results);
return $results;
}
}
$ex = new ex();
var_dump($ex->get_files_deep('_some_path','.less'));
?>
It will retrieve all the files with the matching extension in the path and it's sub directories.
I hope it's what you need.