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'];
Related
So as the title said, I'm struggling to copy a folder to another folder
I tried this but no results
Edit: I got this to work by fixing the $npath variable I was just giving the url without the folder's name $npath = $newk->url;
so the final code will be :
public function copyFolder(Request $request)
{
$id= $request->get('oldf');
$new = $request->get('newf');
$document = Document::find($id);
$newk = Document::find($new);
$npath = $newk->url.'/'.$document->nom;
$file= new Filesystem();
if($file->copyDirectory($document->url, $npath)){
return redirect('home');
}
return redirect('home');
}
any help would be appreciated :)
use this function
function recursive_files_copy($source_dir, $destination_dir)
{
// Open the source folder / directory
$dir = opendir($source_dir);
// Create a destination folder / directory if not exist
if (!is_dir($destination_dir)){
mkdir($destination_dir);
}
// Loop through the files in source directory
while($file = readdir($dir))
{
// Skip . and ..
if(($file != '.') && ($file != '..'))
{
// Check if it's folder / directory or file
if(is_dir($source_dir.'/'.$file))
{
// Recursively calling this function for sub directory
recursive_files_copy($source_dir.'/'.$file, $destination_dir.'/'.$file);
}
else
{
// Copying the files
copy($source_dir.'/'.$file, $destination_dir.'/'.$file);
}
}
}
closedir($dir);
}
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);
}
I'm trying to get the svg files from a folder.
Tried the following ways but none of them seems to work:
<?php
$directory = get_bloginfo('template_directory').'/images/myImages/';
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while ($it->valid()) { //Check the file exist
if (!$it->isDot()) { //if not parent ".." or current "."
if (strpos($it->key(), '.php') !== false
|| strpos($it->key(), '.css') !== false
|| strpos($it->key(), '.js') !== false
) {
echo $it->key() . '<br>';
}
}
}
?>
And:
global $wp_filesystem;
$path = get_bloginfo('template_directory').'/images/myImages/';
$filelist = $wp_filesystem->dirlist( $path );
echo $filelist;
And:
$path = get_bloginfo('template_directory').'/images/myImages/';
$images = scandir( $path, 'svg', $depth = 0);
echo $images;
And:
$dir = get_bloginfo('template_directory').'/images/myImages/';
$files = scandir($dir);
print_r($files);
And:
$directory = get_bloginfo('template_directory')."/images/myImages/";
$images = glob($directory . "*.svg");
echo '<pre>';
print_r($images);
echo '</pre>';
echo $directory.'abnamro.svg">';
foreach($images as $image)
{
echo $image;
}
I'm kinda lost. I might think that there is something else wrong.
Also checked the privileges for the user but all is okay.
I run Wordpress on a local machine with MAMP.
Any thoughts?
Try the function below, I have notated for clarity. Some highlights are:
You can skip dots on outset in the directory iterator
You can trigger a fatal error if path doesn't exist (which is the issue in this case, you are using a domain-root path instead of the server root path [ABSPATH])
You can choose the extension type to filter files
function getPathsByKind($path,$ext,$err_type = false)
{
# Assign the error type, default is fatal error
if($err_type === false)
$err_type = E_USER_ERROR;
# Check if the path is valid
if(!is_dir($path)) {
# Throw fatal error if folder doesn't exist
trigger_error('Folder does not exist. No file paths can be returned.',$err_type);
# Return false incase user error is just notice...
return false;
}
# Set a storage array
$file = array();
# Get path list of files
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::SKIP_DOTS)
);
# Loop and assign paths
foreach($it as $filename => $val) {
if(strtolower(pathinfo($filename,PATHINFO_EXTENSION)) == strtolower($ext)) {
$file[] = $filename;
}
}
# Return the path list
return $file;
}
To use:
# Assign directory path
$directory = str_replace('//','/',ABSPATH.'/'.get_bloginfo('template_directory').'/images/myImages/');
# Get files
$files = getPathsByKind($directory,'svg');
# Check there are files
if(!empty($files)) {
print_r($files);
}
If the path doesn't exist, it will now tell you by way of system error that the path doesn't exist. If it doesn't throw a fatal error and comes up empty, then you actually do have some strange issue going on.
If all goes well, you should get something like:
Array
(
[0] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img1.svg
[1] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img2.svg
[2] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img3.svg
[3] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img4.svg
)
If path invalid, will throw:
Fatal error: Folder does not exist. No file paths can be returned. in /data/19/2/133/150/3412/user/12321/htdocs/domain/index.php on line 123
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.
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.