Change folder to fetch on filemanager - php

I've the following problem: i'm working on a filemanager consisting in only one index.php file, that fetches all the files and folders from the actual folder there its located in.
So if i have a folder with the filemanager file on it:
Folder01
-folder-A
-folder-B
-file1.php
-image.png
-index.php
The filemanager will show: folder-A, folder-B, file1.php and image.png
The problem is I can't change the folder to fetch it's content, to be able to view, by default, the content of folder-A for example.
$file = isset($_REQUEST['file']) ? urldecode($_REQUEST['file']) : '.';
if(isset($_GET['do']) && $_GET['do'] == 'list') {
if (is_dir($file)) {
$directory = $file;
$result = array();
$files = array_diff(scandir($directory), array('.','..'));
foreach($files as $entry) if($entry !== basename(__FILE__)) {
$i = $directory . '/' . $entry;
$stat = stat($i);
$result[] = array(
'mtime' => $stat['mtime'],
'size' => $stat['size'],
'name' => basename($i),
'path' => preg_replace('#^\./#', '', $i),
'ext' => pathinfo($i, PATHINFO_EXTENSION),
'is_dir' => is_dir($i),
'is_deleteable' => (!is_dir($i) && is_writable($directory)) ||
(is_dir($i) && is_writable($directory) && is_recursively_deleteable($i)),
'is_readable' => is_readable($i),
'is_writable' => is_writable($i),
'is_executable' => is_executable($i),
);
}
} else {
err(412,"Not a Directory");
}
echo json_encode(array('success' => true, 'is_writable' => is_writable($file), 'results' =>$result));
exit;
}
This snippet is the beginning of its php code, which is in charge of fetching the files of the selected folder.
Any idea about how to change that?

try glob function, its like dir command in dos,
it will list all of the dirs and files in the current working directory and put them in an array, which is the return value of the function.

Related

How to remove __MACOSX while using ZipArchive

After hours of trying to figure out why php "ZipArchive" does not work as expected, due to Mac OS adding a "__MACOSX" folder in the zip compression process.
How would I go about deleting "__MACOSX" folder in a zip archive during the upload process in a form?
Below is what I'm working with:
<?php
public function uploadZip($file)
{
$advert_index;
$zip = new \ZipArchive;
if (true === $zip->open($file['tmp_name'])) {
$source = trim($zip->getNameIndex(0), '/');
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
// Determine output filename (removing the `$source` prefix).
$substring_name = substr($name, strlen($source)+1);
$file = $this->option['uploads_path'] . $this->option['advert_id'] . '/' . $substring_name;
// Store the adverts `index.html` file URL to be returned.
if ('html' === pathinfo($name, PATHINFO_EXTENSION)) {
$advert_index = basename($name);
}
// Create the directories if necessary.
$dir = dirname($file);
if (! is_dir($dir)) {
mkdir($dir, 0777, true);
}
// Read from Zip and write to disk.
$fpr = $zip->getStream($name);
$fpw = fopen($file, 'w');
while ($data = fread($fpr, 1024)) {
fwrite($fpw, $data);
}
fclose($fpr);
fclose($fpw);
}
$zip->close();
return array(
'status' => true,
'message' => array(
'index' => $advert_index,
'type' => 'text/html', // #HACK: Set MIME type manually. #TODO: Read MIME type from file.
),
);
}
return array(
'status' => false,
'message' => 'Upload failed',
);
}
Any help would be much appreciated :)
Note: I Managed to find the file just can't get it to be removed.
// Check to see the __MACOSX
if($zip->getNameIndex($i) === "__MACOSX/") {
error_log($zip->getNameIndex($i) . ' - Error here continue');
$zip->deleteName("__MACOSX/");
continue; // Move on to the next iteration
// $zip->deleteIndex($i);
} else {
$name = $zip->getNameIndex($i);
}
It was actually very simple, instead to trying to delete the folder within the zip-archive just had to skip all indexes aka filename that begin with a certain string while looping through the files.
if(substr($zip->getNameIndex($i), 0, 9) === "__MACOSX/") {
continue;
} else {
$name = $zip->getNameIndex($i);
}

Open_basedir prevents listing symlink files in php

I have a function which returns the current files in a directory. Sometimes it contains symlinks which point outside of my web directory. Unfortunately, when I add a "open_basedir" restriction in my php ini file, the symlinked files are not visible anymore to PHP.
php.ini file:
[PHP]
...
open_basedir="/var/www"
...
This is partly understandable because the symlink points to a file outside the allowed directory. But I only need the filename of the symlink itself (not the original file). Why PHP cannot see/list the names of a symlinked file is a mystery for me.
I use this function to get the filelist of a directory:
function getFileList($dir)
{
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// open pointer to directory and read list of files
$d = #dir($dir) or die("getFileList: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
if(is_dir("$dir$entry")) {
$retval[] = array(
"name" => "$dir$entry/",
"type" => filetype("$dir$entry"),
"size" => 0,
"lastmod" => filemtime("$dir$entry")
);
} elseif(is_readable("$dir$entry")) {
$retval[] = array(
"name" => "$dir$entry",
"type" => mime_content_type("$dir$entry"),
"size" => filesize("$dir$entry"),
"lastmod" => filemtime("$dir$entry")
);
}
}
$d->close();
return $retval;
}
Should I use another function or is this some kind of glitch in PHP?

php - get sub-sub-folder and specific files name and path

I would to retrieve from a path all sub (and sub-sub) directories and all files (only with .php and .css extensions) in (last sub) it.
The structre is the following:
my_path/sub-folder1/ // I want to get the sub folder name (and check if allowed)
sub-sub-folder1/file1.php // I want to get the file name and path
sub-sub-folder1/file1.css // I want to get the file name and path
sub-sub-folder2/file2.php // ....
sub-sub-folder2/file2.css
sub-sub-folder3/file3.php
sub-sub-folder3/file3.css
my_path/sub-folder2/
sub-sub-folder1/file1.php
sub-sub-folder1/file1.css
sub-sub-folder2/file2.php
sub-sub-folder2/file2.css
sub-sub-folder3/file3.php
sub-sub-folder3/file3.css
I know the my_pathdirectory name. About sub-folder, I only want to retrieve sub-folder which have the name (sub-folder1, sub-folder2 for example). And I would like to retrieve all sub-sub-folders and inside them and get the name and path of the .css and .php files inside it. I'm not sure if I'm clear with my explanations.
My aim is to store all this information in an array like this:
$data['sub-folder-1']= array(
'sub-sub-folder1' => array(
'name' => 'file1',
'php' => 'file1.php',
'css' => 'file1.css',
),
'sub-sub-folder2' => array(
'name' => 'file2',
'php' => 'file2.php',
'css' => 'file2.css',
),
...
);
$data['sub-folder-2']= array(
'sub-sub-folder1' => array(
'name' => 'file1',
'php' => 'file1.php',
'css' => 'file1.css',
),
'sub-sub-folder2' => array(
'name' => 'file2',
'php' => 'file2.php',
'css' => 'file2.css',
),
...
);
I have started with this code but I have some difficulties to make it works (and it's not finished), I don't use this kind of functionnality a lot...
$dirname = 'my_path';
$findphp = '*.php';
$findcss = '*.css';
$types = array('sub-folder1','sub-folder2');
$sub_dirs = glob($dirname.'/*', GLOB_ONLYDIR|GLOB_NOSORT);
if(count($sub_dirs)) {
foreach($sub_dirs as $sub_dir) {
$sub_dir_name = basename($sub_dir);
if (in_array($sub_dir_name,$types)) {
$sub_sub_dirs = glob($sub_dir.'/*', GLOB_ONLYDIR|GLOB_NOSORT);
if(count($sub_sub_dirs)) {
foreach($sub_sub_dirs as $sub_sub_dir) {
$php = glob($sub_sub_dir.'/'.$findphp);
$css = glob($sub_sub_dir.'/'.$findcss);
$sub_sub_dir_name = basename($sub_sub_dir);
$data[$sub_dir_name][$sub_sub_dir_name]['type'] = $sub_dir_name;
$data[$sub_dir_name][$sub_sub_dir_name]['name'] = basename($php[0], '.php');
$data[$sub_dir_name][$sub_sub_dir_name]['html'] = $php[0];
$data[$sub_dir_name][$sub_sub_dir_name]['css'] = $css[0];
}
}
}
}
} else {
echo "Nothing was found.";
}
print_r($data);
I like using the RecursiveDirectoryIterator class. I think it's more readable. This sample allow you to read all subfolders of a given source.
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source)); // Top source directory
$iterator->setFlags(\FilesystemIterator::SKIP_DOTS); // Skip folders with dot
$allowedExtension = array('php', 'css'); // And other if needed
$skin = array();
while ($iterator->valid()) {
$extension = $iterator->getExtension(); // >= PHP 5.3.6
if ($iterator->isFile() && in_array($extension, $allowedExtension)) {
// Complete this part or change it following your needs
switch ($extension) {
case 'php':
// All your logic here
$skin[$iterator->getPath()]['name'] = $iterator->getFileName(); //eg
break;
default:
break;
}
}
$iterator->next();
}
You can find the whole list of available functions at Directory Iterator.
Hope it's help.

Php read directory with absolute path

I have this php script which reads mp3 files from the directory:
// Set your return content type
header('Content-type: text/xml');
//directory to read
$dir = ($_REQUEST['dir']);
$sub_dirs = isBoolean(($_REQUEST['sub_dirs']));
if(file_exists($dir)==false){
//echo $_SERVER['DOCUMENT_ROOT'];
//echo "current working directory is -> ". getcwd();
echo 'Directory \'', $dir, '\' not found!';
}else{
$temp = getFileList($dir, $sub_dirs);
echo json_encode($temp);
}
function isBoolean($value) {
if ($value && strtolower($value) !== "false") {
return true;
} else {
return false;
}
}
function getFileList($dir, $recurse){
$retval = array(); // array to hold return value
if(substr($dir, -1) != "/") // add trailing slash if missing
$dir .= "/"; // open pointer to directory and read list of files
$d = #dir($dir) or die("getFileList: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) { // skip hidden files
if($entry[0] == "." || $entry[0] == "..") continue;
if(is_dir("$dir$entry")) {
if($recurse && is_readable("$dir$entry/")) {
$retval = array_merge($retval, getFileList("$dir$entry/", true));
}
}else if(is_readable("$dir$entry")) {
$path_info = pathinfo("$dir$entry");
if(strtolower($path_info['extension'])=='mp3'){
$retval[] = array(
"path" => "$dir$entry",
"type" => $path_info['extension'],
"size" => filesize("$dir$entry"),
"lastmod" => filemtime("$dir$entry")
);
}
}
}
$d->close();
return $retval;
}
This file sits in the same directory as the html page which executes the script. For example, I pass the relative path 'audio/mp3' or '../audio/mp3' and it all works well.
Is it possible to make this read directory with absolute path?
For example, if I would pass this: http://www.mydomain.com/someFolder/audio/mp3, and html page which executes the script and the php file would be placed in this location: http://www.mydomain.com/someFolder/
Thank you!
Web root is always just /. You'd never need the hostname or protocol part, and root can be only root of the server, not some folder or file.
If you need some path, like /testthesis/ - there are ways, but it has nothing common with web root.
If you need a filesystem directory for the webroot - it's in the $_SERVER['DOCUMENT_ROOT'] variable.

codeigniter get directory info in view

I'm essentially having difficulty pass dynamic variables to a view.
I have php functions as the following:
public function scandir_recursive($directory, $filter=FALSE)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}elseif(is_readable($directory))
{
// initialize directory tree variable
$directory_tree = array();
// we open the directory
$directory_list = opendir($directory);
// and scan through the items inside
while (FALSE !== ($file = readdir($directory_list)))
{
// if the filepointer is not the current directory
// or the parent directory
if($file != '.' && $file != '..')
{
// we build the new path to scan
$path = $directory.'/'.$file;
// if the path is readable
if(is_readable($path))
{
// we split the new path by directories
$subdirectories = explode('/',$path);
// if the new path is a directory
if(is_dir($path))
{
// add the directory details to the file list
$directory_tree[] = array(
'path' => $path,
'name' => end($subdirectories),
'kind' => 'directory',
// we scan the new path by calling this function
'content' => scandir_recursive($path, $filter));
// if the new path is a file
}elseif(is_file($path))
{
// get the file extension by taking everything after the last dot
$extension = end(explode('.',end($subdirectories)));
// if there is no filter set or the filter is set and matches
if($filter === FALSE || $filter == $extension)
{
// add the file details to the file list
$directory_tree[] = array(
'path' => $path,
'name' => end($subdirectories),
'extension' => $extension,
'size' => filesize($path),
'kind' => 'file');
}
}
}
}
}
// close the directory
closedir($directory_list);
// return file list
return $directory_tree;
// if the path is not readable ...
}else{
// ... we return false
return FALSE;
}
}
</code>
I need to make such a function operable in the sense I can echo the data retrieved from the directories recursively and pass this data to the view.
In the controller do the following:
$data['directory_tree'] = scandir_recursive($directory);
$this->load->view('my_view', $data);
In the view you can access the variable like this:
echo $directory_tree['path'];

Categories