Let’s say we have a site with this address: https://example.com
and we have a directory inside like: https://example.com/directory
And that’s all we know, we don’t know what folders are inside directory
folder.
How to get all the paths of files inside the directory
folder and pass the result to a javascript array:
The desired result would be something like this in javascript:
let paths = [
'https://example.com/directory/audio/song_1.mp3',
'https://example.com/directory/audio/song_2.mp3',
'https://example.com/directory/picture/image_1.png',
'https://example.com/directory/picture/image_2.jpg',
'https://example.com/directory/movie/clip.mp4',
];
I have tried all the possible solutions on the net but it seems that I can’t find a working one without help.
one level above the directory
folder I have the test.php:
<?php
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($value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
echo json_encode(getDirContents('directory'));
It returns the result like this:
“/storage/ssd4/693/8074693/public_html/directory/audio/song_1.mp3”
[3]=> string(72)
“/storage/ssd4/693/8074693/public_html/directory/audio/song_2.mp3”
[4]=> string(72)
“/storage/ssd4/693/8074693/public_html/directory/picture/image_1.png”
[5]=> string(75)
“/storage/ssd4/693/8074693/public_html/directory/picture/image_2.jpg”
[6]=> string(61)
“/storage/ssd4/693/8074693/public_html/directory/movie/clip.mp4” [7]=>
string(73)
The javascript code thanks to @mamoun othman:
$(document).ready( function() {
$.ajax({
type: 'POST',
url: '../test.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
console.log(result)
},
});
});
I have script.js and index.html in another folder at https://example.com/script
.
I can log the PHP $results
using ajax call but still, I get system file paths instead of corresponding URLs!
2
Answers
instead of
var_dump()
usejson_encode(getDirContents('directory'))
, the only way to get all paths in the directory, is to use PHP to loop through files and return the output as JSON or XML (or maybe text but then you have to parse it), JSON is the way to go in your case, all you have to do is request the path of this php script using Ajax:For Ajax call:
It’s a little bit too late, but maybe for someone in the future.
I got all my file paths with this JS code.