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;
}
Related
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 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;
}
}
}
In my server I have folders and sub-directory
I want to call a flatten methode to a directory to move every files at the same level and remove all empty folders
Here is what i've done so far:
public function flattenDir($dir, $destination=null) {
$files = $this->find($dir . '/*');
foreach ($files as $file) {
if(!$destination){
$destination = $dir . '/' . basename($file);
}
if (!$this->isDirectory($file)) {
$this->move($file, $destination);
}else{
$this->flattenDir($file, $destination);
}
}
foreach ($files as $file) {
$localdir = dirname($file);
if ($this->isDirectory($localdir) && $this->isEmptyDirectory($localdir) && ($localdir != $dir)) {
$this->remove($localdir);
}
}
}
public function find($pattern, $flags = 0) {
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
$files = array_merge($files, $this->find($dir . '/' . basename($pattern), $flags));
}
return $files;
}
This code dont show any error on run, but the resukt is not as expected.
For exemple if I have /folder1/folder2/file I want to have /folder2/file as a result but here the folders still like they where ...
I finally make my code works, I post it here in case it help someone
I simplified it to make it more efficient. By the way this function is part of a filemanager classe I made, so I use function of my own class, but you can simply replace $this->move($file, $destination); by move($file, $destination);
public function flattenDir($dir, $destination = null) {
$files = $this->find($dir . '/*');
foreach ($files as $file) {
$localdir = dirname($file);
if (!$this->isDirectory($file)) {
$destination = $dir . '/' . basename($file);
$this->move($file, $destination);
}
if ($this->isDirectory($localdir) && $this->isEmptyDirectory($localdir) && ($localdir != $dir)) {
$this->remove($localdir);
}
}
}
I am trying to remove a directory with rmdir, but I received the 'Directory not empty' message, because it still has files in it.
What function can I use to remove a directory with all the files in it as well?
There is no built-in function to do this, but see the comments at the bottom of http://us3.php.net/rmdir. A number of commenters posted their own recursive directory deletion functions. You can take your pick from those.
Here's one that looks decent:
function deleteDirectory($dir) {
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
You could just invoke rm -rf if you want to keep things simple. That does make your script UNIX-only, so beware of that. If you go that route I would try something like:
function deleteDirectory($dir) {
system('rm -rf -- ' . escapeshellarg($dir), $retval);
return $retval == 0; // UNIX commands return zero on success
}
function rrmdir($dir)
{
if (is_dir($dir))
{
$objects = scandir($dir);
foreach ($objects as $object)
{
if ($object != '.' && $object != '..')
{
if (filetype($dir.'/'.$object) == 'dir') {rrmdir($dir.'/'.$object);}
else {unlink($dir.'/'.$object);}
}
}
reset($objects);
rmdir($dir);
}
}
You could always try to use system commands.
If on linux use: rm -rf /dir
If on windows use: rd c:\dir /S /Q
In the post above (John Kugelman) I suppose the PHP parser will optimize that scandir in the foreach but it just seems wrong to me to have the scandir in the foreach condition statement.
You could also just do two array_shift commands to remove the . and .. instead of always checking in the loop.
Can't think of an easier and more efficient way to do that than this
function removeDir($dirname) {
if (is_dir($dirname)) {
$dir = new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST) as $object) {
if ($object->isFile()) {
unlink($object);
} elseif($object->isDir()) {
rmdir($object);
} else {
throw new Exception('Unknown object type: '. $object->getFileName());
}
}
rmdir($dirname); // Now remove myfolder
} else {
throw new Exception('This is not a directory');
}
}
removeDir('./myfolder');
My case had quite a few tricky directories (names containing special characters, deep nesting, etc) and hidden files that produced "Directory not empty" errors with other suggested solutions. Since a Unix-only solution was unacceptable, I tested until I arrived at the following solution (which worked well in my case):
function removeDirectory($path) {
// The preg_replace is necessary in order to traverse certain types of folder paths (such as /dir/[[dir2]]/dir3.abc#/)
// The {,.}* with GLOB_BRACE is necessary to pull all hidden files (have to remove or get "Directory not empty" errors)
$files = glob(preg_replace('/(\*|\?|\[)/', '[$1]', $path).'/{,.}*', GLOB_BRACE);
foreach ($files as $file) {
if ($file == $path.'/.' || $file == $path.'/..') { continue; } // skip special dir entries
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($path);
return;
}
There are plenty of solutions already, still another possibility with less code using PHP arrow function:
function rrmdir(string $directory): bool
{
array_map(fn (string $file) => is_dir($file) ? rrmdir($file) : unlink($file), glob($directory . '/' . '*'));
return rmdir($directory);
}
Here what I used:
function emptyDir($dir) {
if (is_dir($dir)) {
$scn = scandir($dir);
foreach ($scn as $files) {
if ($files !== '.') {
if ($files !== '..') {
if (!is_dir($dir . '/' . $files)) {
unlink($dir . '/' . $files);
} else {
emptyDir($dir . '/' . $files);
rmdir($dir . '/' . $files);
}
}
}
}
}
}
$dir = 'link/to/your/dir';
emptyDir($dir);
rmdir($dir);
From http://php.net/manual/en/function.rmdir.php#91797
Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.
<?php
public static function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
?>
Try the following handy function:
/**
* Removes directory and its contents
*
* #param string $path Path to the directory.
*/
function _delete_dir($path) {
if (!is_dir($path)) {
throw new InvalidArgumentException("$path must be a directory");
}
if (substr($path, strlen($path) - 1, 1) != DIRECTORY_SEPARATOR) {
$path .= DIRECTORY_SEPARATOR;
}
$files = glob($path . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
_delete_dir($file);
} else {
unlink($file);
}
}
rmdir($path);
}
I didn't arrive to delete a folder because PHP said me it was not empty. But it was. The function by Naman was the good solution to complete mine. So this is what I use :
function emptyDir($dir) {
if (is_dir($dir)) {
$scn = scandir($dir);
foreach ($scn as $files) {
if ($files !== '.') {
if ($files !== '..') {
if (!is_dir($dir . '/' . $files)) {
unlink($dir . '/' . $files);
} else {
emptyDir($dir . '/' . $files);
rmdir($dir . '/' . $files);
}
}
}
}
}
}
function deleteDir($dir) {
foreach(glob($dir . '/' . '*') as $file) {
if(is_dir($file)){
deleteDir($file);
} else {
unlink($file);
}
}
emptyDir($dir);
rmdir($dir);
}
So, to delete a directory and recursively its content :
deleteDir($dir);
With this function, you will be able to delete any file or folder
function deleteDir($dirPath)
{
if (!is_dir($dirPath)) {
if (file_exists($dirPath) !== false) {
unlink($dirPath);
}
return;
}
if ($dirPath[strlen($dirPath) - 1] != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file)
(is_dir("$dir/$file")) ? delTree("$dir/$file") : #unlink("$dir/$file");
return #rmdir($dir);
}