skip to Main Content

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


  1. instead of var_dump() use json_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:

    <?php
    function getDirContents($dir, &$results = array()){
        $files = array_diff(scandir($dir), array('..', '.'));;
        foreach($files as $key => $value){
            $path = $dir.DIRECTORY_SEPARATOR.$value;
            if(is_dir($path)) {
              getDirContents($path, $results);
            } else {
              // change this to https if you have HTTPS
              // or have it as a variable like this :
              // $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
              $directory_path = basename($_SERVER['REQUEST_URI']);
              $results[] =  'http://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
            }
        }
    
        return $results;
    }
    
    echo json_encode(getDirContents('directory'));
    

    For Ajax call:

    $(document).ready(function() {
      $.ajax({
        type: 'POST',
        url: '../test.php',
        data: 'id=testdata',
        dataType: 'json',
        cache: false,
        success: function(result) {
          console.log(result)
        },
      });
    });
    
    Login or Signup to reply.
  2. It’s a little bit too late, but maybe for someone in the future.

    I got all my file paths with this JS code.

    let htmlContainer = document.createElement('div');                  
    
    fetch("http://192.168.0.9:5500/assets/img/gallery/project-1", {
            headers : { 
          'Content-Type': 'text/html',
          'Accept': 'text/html',
          
         }
    }).then(response => response.text())
        .then((stringHtml) => {
            htmlContainer.innerHTML = stringHtml;            //convert plain text to Html to have   
                                                             //acces to its elements
                                                             
            //htmlContainer will containe html representation
            //of our project diretories and files, so from there
            //will be able to get files paths
           console.log( Array.from(htmlContainer
                                .querySelector('#files')
                                    .querySelectorAll("li>a"))
                                        .map( x => x.getAttribute('href'))) //will print an array
                                                                            //with all file and direcotory paths in our directory
            
        })
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search