PHP - Create a directory listing of specified folder - javascript

I've got small piece of code which I'm using to scan a certain directory on my server for all the files and folders inside. But there's a catch... It can only scan the specified folder, and no sub-directories. Let's say share/ is the root directory for this scan, if there are files in any sub-directory like share/folder/file.png they won't be listed, where the entire purpose of my project is to create an HTML file explorer.
This is the code I'm using to receive the list of files from the server to later display it in the browser using JavaScript:
<?php
$listFiles = array();
if ($handle = opendir('./share')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$listFiles[] = $entry;
}
}
closedir($handle);
}
$FS_files = json_encode($listFiles);
?>
And then I "push" it rude to my actual JavaScript code like this:
let FS_files = <?php echo $FS_files ?>
The code I above basically generates an array of file names from scanned directory. What I wanna know is how can I get an entire JSON tree of files in this directory and all folders inside it, or possibly change my code so it works that way?

<?php
function scanFolder($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value,array(".",".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
$result[$value] = scanFolder($dir . DIRECTORY_SEPARATOR . $value);
} else {
$result[] = $value;
}
}
}
return $result;
}
$FS_files = json_encode(scanFolder("./share"));
?>
The function scans the folder and checks each entry with is_dir. If its true, this folder is scanned with the same function.

Related

Working solution to get file names inside server folder

I've used multiple solutions here on Stackoverflow but I can't make any of them work properly (Nodejs is not accepted).
I have a path filled with mp3 files and I want to return the file names.
The lasted thing I tried was this:
in the getFiles folder of my server, I have a PHP file named files.php and a JS file named scripts.js and index.html
PHP code:
<?php
$dir = 'mysite/folderOf/audio/';
// Store the scandir results in a variable
$files = scandir($dir);
// Encode the array in JSON and echo it
echo json_encode($files);
?>
Javascript:
$.get( "files.php", function( data ) {
console.log(data);
});
The directory where the mp3 files exist is: mysite/folderOf/audio/
The result of the code above is:
I need to return an array with filenames of mysite/folderOf/audio/ directory.
try this if it works
<?php
// open this directory
$Directory = opendir('mysite/folderOf/audio');
// get each entry
while($entryName = readdir($Directory)) {
$fileArray[] = $entryName;
}
// close directory
closedir($Directory);
// count elements in array
sort($fileArray);
$indexCount = count($fileArray);
// loop through the array of files and print them all in a list
for($index=0; $index < $indexCount; $index++) {
$extension = substr($fileArray[$index], -3);
if ($extension == 'mp3'){
echo '<a class="iconMP3" href="mysite/folderOf/audio/' . $fileArray[$index] . '"/>' . $fileArray[$index] . '</a>';
}
}
?>

I want to fetch all dir name

I need seniors help to make dropdown list of root directories using php. I created almost but having one issue is not getting root directory.
Like home/abc/ all dir I want
Code sample
<?
$dirs = array_filter(glob('/*'), 'is_dir'); //this code getting main root folders
print_r($dirs); // array showing root directory
?>
But I want to get all directories from home/username
is it possible?
Despite the clarification to the question I'm not 100% sure the following is what you are meaning. I took it to be that you wish to get all folders under the start location - in your case /home/username
The recursiveIterator classes are very useful for this sort of task.
/* The ROOT directory you wish to scan */
$dir = 'c:/wwwroot/images';
if( realpath( $dir ) ){
$dirs=array();
$dirItr=new RecursiveDirectoryIterator( realpath( $dir ), RecursiveDirectoryIterator::KEY_AS_PATHNAME );
foreach( new RecursiveIteratorIterator( $dirItr, RecursiveIteratorIterator::CHILD_FIRST ) as $file => $info ) {
if( $info->isDir() ) $dirs[]=realpath( $info->getPathName() );
}
echo '<pre>',print_r( $dirs, 1 ),'</pre>';
}
Loop through user's directory
The following code finds the user directory (compatible with Windows, Mac, and Linux) then recursively echo's the directory paths.
<?php
$dir = '';
if (strpos(php_uname(),"Linux") === 0) {
//linux
$dir = "/home/";
} else {
//windows and mac
$dir = "/users/";
}
$dir.=get_current_user();
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
echo $fileinfo->getPathName() . "\n";
// recursion goes here.
}
}
?>
Looping through the entire System
The AJAX method
Ajax is basically just a way of communicating to a server without having to refresh. What the following code does it lazy loads directories. So, as it's needed, it will load the next iteration for directories. I believe this would be what you want because printing everything from the root is a bit suicidal.
<?php
function filterDirectories($dir) {
$myDirs = scandir($_POST['dir']);
foreach ($myDirs as $key => $myDir) {
$path = str_replace('//','/',$dir . '/' . $myDir);
if (!is_dir($path) || $myDir === "." || $myDir === "..") {
unset($myDirs[$key]);
} else {
$myDirs[$key] = $path;
}
}
return array_values($myDirs);
}
if (isset($_POST['dir'])) {
echo json_encode(filterDirectories($_POST['dir']));
die();
}
?>
<body>
<form>
<div id="selectContainer">
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function () {
"use strict";
var rootDir = "/";
function getDirectory(dir) {
$.post("#", {
dir : dir
}, function (data) {
var $select = $("<select>");
for (var i = 0, len = data.length; i < len; i++) {
$("<option>")
.text(data[i])
.attr('value',data[i])
.appendTo($select);
}
$("#selectContainer").append($select);
}, "json");
}
getDirectory(rootDir);
$("#selectContainer").on("change", "select", function () {
$(this).nextAll().remove();
getDirectory($(this).val());
});
});
</script>

Active PHP code using JavaScript and URL

I have a self destruct PHP code that would delete all files and folders in my domain's directory.
<?Php
$dir = 'C:\wamp64\www\FileDirectory' . DIRECTORY_SEPARATOR . 'Files';
$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
if ($file->isDir()){
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($dir);
$filename = 'C:\wamp64\www\FileDirectory\Files';
if (file_exists($filename)) {
echo "The Directory has not been deleted";
} else {
echo "All Files And Folders Are Deleted";
}
?>
I need a way to only activate this code when I type in extra code to the end of my URL. I thought you could do that with JavaScript but I'm not too certain. Please let me know if I can do this. If I have to use a different code to do so, it's not a big deal.
Use $_GET['parameter'] to get parameter from get method:
http://example.com/index.php?doClean=1
if (isset($_GET['doClean'])) {
// Your code goes here
}

Codeigniter: write_file() returns false

public function ExportCSV()
{
// THIS PART IS WORKING
$this->load->dbutil();
$this->load->helper('file');
$delimiter = ',';
$newline = "\n";
$enclosure = '"';
$filename = "tamp.csv";
$query = "SELECT politician.id, politician.ident, party.abbr, politician.id_image, politician.name, politician.surname, politician.personal_birth, politician.home_city, politician.political_function
FROM politician
INNER JOIN party
WHERE party.id = politician.id_party
LIMIT 10000";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline, $enclosure);
// data IS CORRECT
// THIS PART NOT WORKING: write_file() returns false
if ( ! write_file(APPPATH."/assets/media/upload/tamp.csv", $data, 'r+'))
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
}
The variable $data contains the correct output but the write_file() returns false.
The directory /assets/ is in the main directory of the codeigniter project.
My questions are:
Is this function returning false because I don't have the permission to write in this directory?
If yes, what should I do?
In which directory should I write this file as I would like it public?
When creating a file with write_file make sure your folder/directory is there where you would like to create file
Then I would recommend using FCPATH
$data = "Some file data";
if (write_file(FCPATH . '/document/text.txt', $data) == FALSE)
{
echo 'Unable to write the file';
} else {
echo 'File written!';
}
My directory
application
document
system
index.php

get all images in an array from directory and sub-directories

Currently I've similar to the following tree structure:
+images
+sub-directory
-image1.jpg
-image2.jpg
+sub-directory-2
-image3.jpg
-image4.jpg
-some-image.jpg
-another.jpg
<script>
<?php
//path to directory to scan. i have included a wildcard for a subdirectory
$directory = "images/*/";
//get all image files with a .jpg extension.
$images = glob("" . $directory . "*.jpg");
$imgs = '';
// create array
foreach($images as $image){ $imgs[] = "$image"; }
echo "var allImages = ".$imgs.";\n";
?>
console.log(allImages);
</script>
As I'm extremely new to php, I'm blindly getting logged as Array() in the console.
Also, I've set $directory = "images/*/"; which will get all images inside the subfolders only but not getting images inside parent directory that likely to images/some-image.jpg and I wanted to get this too.
I want all the images in an array like this (when I use console.log(allImages);):
['some-image.jpg','another.jpg','image1.jpg','image2.jpg','image3.jpg','image4.jpg']
I love JSON, keeps things nice and simple:
<?php
$images = glob("images/*/*.jpg");
$imgs = array();
foreach($images as $image){ $imgs[] = $image; }
?>
<script>
var allImages = JSON.parse('<?php echo json_encode($imgs);?>');
console.log( allImages);
</script>
Now you have the php array available in javascript, with the same structure. You can loop them with a for, of if you have jQuery, $.each().
I changed a code more to your style (mixing php and html), but you should try to split those in htmltemplates.
Im not 100% sure about this, but you can regex in your glob, if this works you don't need the foreach, this will return only the filenames:
$images = glob("~(?:images/*/)*\.jpg~");
What about this:
<script>
<?php
$directory = "images/*/";
$images = glob("" . $directory . "*.jpg");
echo "var allImages = ['".implode("', '", $images)."'];\n";
?>
console.log(allImages);
</script>
How about a recursive function?
function loadImages($folder)
{
$files = glob($folder);
foreach( $files as $file )
{
if(is_dir($file))
{
loadImages($file);
} else {
$images[] = $file; // add some file type validation here
}
}
return $images;
}
$images = json_encode(loadImages($startFolderPath));
I'm on an iPad so I can't test it.

Categories