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

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.

Related

CKFinder - Folder not found While Uploading Files on Server

I'm trying to integrate CKFinder(v.3) with CKEditor(v.4) in my Codeigniter project but getting error "Folder not found" when i tried to upload a file on to server. I hv googled this issue and tried various solutions like below but none had worked:
1) Changing permission for ckfinder folder to FULL for all users
2) Changing permission for data-content/page_assets folder to FULL for all users
3) Set baseURL path in config.php to "http://localhost:8080/project/cms/js/ckfinder/userfiles/"
Below are the editor setup in my view file
// filebrowserBrowseUrl & filebrowserUploadUrl will be different for each module but the base will
// same 'data-content'
CKEDITOR.replace( 'page_content', {
filebrowserBrowseUrl: '<?php echo base_url()?>js/ckfinder/ckfinder.html?Type=Images&rlf=0&start=Images:/project/data-content/page_assets/',
filebrowserUploadUrl: '<?php echo base_url()?>js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images&currentFolder=/project/data-content/page_assets/',
filebrowserWindowWidth: '1000',
filebrowserWindowHeight: '700'
});
Below are the config.php in CKFinder. Listing only what i had changed in this file
$config['authentication'] = function () {
return true;
};
$config['backends'][] = array(
'name' => 'default',
'adapter' => 'local',
//'baseUrl' => '/ckfinder/userfiles/',
'baseUrl' => 'http://localhost:8080/project/cms/js/ckfinder/userfiles/',
// 'root' => '', // Can be used to explicitly set the CKFinder user files directory.
'chmodFiles' => 0777,
'chmodFolders' => 0755,
'filesystemEncoding' => 'UTF-8',
);
$config['overwriteOnUpload'] = false;
$config['checkDoubleExtension'] = true;
$config['disallowUnsafeCharacters'] = true;
$config['secureImageUploads'] = true;
$config['checkSizeAfterScaling'] = true;
$config['htmlExtensions'] = array('html', 'htm', 'xml', 'js');
$config['hideFolders'] = array('.*', 'CVS', '__thumbs');
$config['hideFiles'] = array('.*');
$config['forceAscii'] = false;
$config['xSendfile'] = false;
// https://ckeditor.com/docs/ckfinder/ckfinder3-php/configuration.html#configuration_options_debug
$config['debug'] = true;
Detail error, after debugging on
Fatal error: Uncaught CKSource\CKFinder\Exception\FolderNotFoundException: Folder not found in C:\xampp\htdocs\project\cms\js\ckfinder\core\connector\php\vendor\cksource\ckfinder\src\CKSource\CKFinder\Filesystem\Folder\WorkingFolder.php:144
These are the concerned code block from WorkingFolder.php file
// Check if resource type folder exists - if not then create it
$currentCommand = (string) $request->query->get('command');
$omitForCommands = array('Thumbnail');
// DEBUGGING the value of EACH PROPERTY
// clientCurrentFolder => /noveltech/data-content/page_assets/
// $currentCommand => QuickUpload
// $resourceTypeDirectory => images
// $this->path => images/noveltech/data-content/page_assets/
if (!in_array($currentCommand, $omitForCommands) && !empty($resourceTypeDirectory) && !$backend->hasDirectory($this->path))
{
if ($this->clientCurrentFolder === '/') {
#$backend->createDir($resourceTypeDirectory);
if (!$backend->hasDirectory($resourceTypeDirectory))
{
throw new AccessDeniedException("Couldn't create resource type directory. Please check permissions.");
}
}
else {
throw new FolderNotFoundException(); // THIS IS LINE NO. 144
}
}
My development environment is XAMPP.
Can any one please help me in integrating CKFinder?
Much Regards,
Javed

Can you do move_uploaded_file by $_FILES['name'] instead of $_FILES['tmp_name'] in php

I am trying to loop through an array of variables of type '$_FILES' posted from a form and process each image and store directories
The code is
if(isset($_POST['travsubli'])){
$date=Date('Y-m-d');
$uname=substr($utravlastname,0,5).substr($utravphone,5,10);
$destin=str_replace(array(" ","/","."),"-",$_POST['Destination']);
if(!is_dir("images/userimages/travelphotos")) {mkdir("images/userimages/travelphotos");}
if(!is_dir("images/userimages/travelphotos/$uname")){mkdir("images/userimages/travelphotos/$uname");}
echo "Check : ".$_FILES['TourPhoto1']['name']."<br>";
$photosarray=array($_FILES['TourPhoto1']['name'],$_FILES['TourPhoto2']['name'],$_FILES['TourPhoto3']['name'],$_FILES['TourPhoto4']['name'],$_FILES['TourPhoto5']['name'],$_FILES['TourPhoto6']['name']);
$pai=1;
foreach($photosarray as $pha){
$ext=pathinfo($pha,PATHINFO_EXTENSION);
if(!empty($ext)){
$newphotoname="Travelogue-Photo-$destin-$pai.$ext";
$newphotopath="images/userimages/travelphotos/$uname/$newphotoname";
if(move_uploaded_file($pha,$newphotopath)){
echo "Photo Successfully Uploaded !<br>";
}else{echo "Something went wrong with Photo Upload !<br>"; $e=error_get_last();echo $e['message']."<br>";}
}
$TourPhoto="TourPhoto$pai";
$$TourPhoto=$newphotoname;
echo $pha."->$TourPhoto->".$$TourPhoto.$pai."<br>";
$pai++;
}
My question or rather propblem is,
Move_uploaded_file does not work.
I presume it is because I am using $_FILES['variable']['name'] instead of $_FILES['variable']['tmp_name'] in the move_uploaded_file command.
Am I right in my diagnosis ? If so, what should be done ? Because, I have assigned 'name' parameter in the array to loop. How do I undo it to 'tmp_name' inside the loop ? Or is there any other better alternative ?
I don't know what real problem is but you can try this:
$photosarray = array(
array(
'tmp_name' => $_FILES['TourPhoto1']['tmp_name'],
'real_name' => $_FILES['TourPhoto1']['name'],
),
array(
'tmp_name' => $_FILES['TourPhoto2']['tmp_name'],
'real_name' => $_FILES['TourPhoto2']['name'],
),
array(
'tmp_name' => $_FILES['TourPhoto3']['tmp_name'],
'real_name' => $_FILES['TourPhoto3']['name'],
),
// etc
);
foreach ($photosarray as $pha) {
$ext = pathinfo($pha['real_name'],PATHINFO_EXTENSION);
$path = '';
// make your path here
// copy file
move_uploaded_file($pha['tmp_name'], $new_path);
// do other stuff
}

Change folder to fetch on filemanager

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.

PHP - PCLZIP adding file from string

PCLZIP is a great library, but unfortunately it is poorly documented.
I am using it in order to support also servers where ZipArchive is disabled (or php version not supported)
I have a function to add uploaded files (one by one) to a ZIP archive.
If the archive is not existing, it creates one, if the archive exists, it just adds the new files.
The problem I have is with a function adding a TXT file, that is based on the Comments from the archive. (the function reads the comments that were previously prepared, and should create a TXT file from string and insert into the archive.)
I can not seem to find a function to OVERWRITE a file from string (Or I do not know how to use it ).
I can create it with PCLZIP_ATT_FILE_NAME ,but somehow, when I run the function, it creates a new .txt file (with the same filename!) every time it adds a file to the archive (as opposed to OVERWRITE the existing one)
I tried to use PCLZIP_ATT_FILE_NEW_FULL_NAME - but I can not find where to give it the parameters to WHICH file it needs to overwrite ..
The function is here : (sorry if it is long..)
$archive = new PclZip($zipname);
if (!file_exists($zipname)){ //The Archive already exists - let´s just ADD new files.
$comment = $comment_head . $comment_add ;
$string_content = $comment;
$v_list = $archive->create($file,
PCLZIP_OPT_ADD_PATH, $sitename,
PCLZIP_OPT_COMMENT, $comment,
PCLZIP_OPT_REMOVE_ALL_PATH);
$prop = $archive->properties();
$prop = $prop['comment'];
if (!$prop) {$prop = $comment;}
$list = $archive->add(array(
array(
PCLZIP_ATT_FILE_NAME => $string_file,
PCLZIP_ATT_FILE_CONTENT => $prop,
PCLZIP_ATT_FILE_NEW_FULL_NAME => $string_file
)
)
);
if ($v_list == 0) {
die("Error : ".$archive->errorInfo(true));
}
} else {
// No Archive already exists - Create with new file .
$comment_add = $meta['file'] . PHP_EOL . PHP_EOL ;/*.$comment_foot*/ ;
$b_list = $archive->add($file,
PCLZIP_OPT_ADD_PATH, $sitename,
PCLZIP_OPT_ADD_COMMENT, $comment_add,
PCLZIP_OPT_REMOVE_ALL_PATH);
$prop = $archive->properties();
$prop = $prop['comment'];
if (!$prop) {$prop = $comment;}
$list_6 = $archive->add(array(
array( PCLZIP_ATT_FILE_NAME => $string_file,
PCLZIP_ATT_FILE_CONTENT => $prop
)
)
);
if ($b_list == 0) {
die("Error : ".$archive->errorInfo(true));
}
}
So - anyone knows how to OVERWRITE a file from string (and not from file..) with PCLzip ??
$archive = new PclZip("archive.zip");
$v_filename = "new_file.txt";
$v_content = "This is the content of file one\nHello second line";
$list = $archive->create(array(
array( PCLZIP_ATT_FILE_NAME => $v_filename,
PCLZIP_ATT_FILE_CONTENT => $v_content
)
)
);
if ($list == 0) {
die("ERROR : '".$archive->errorInfo(true)."'");
}
http://www.phpconcept.net/pclzip/news/3-pclzip-26

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