Search code examples
phpdirectoryscandir

Get all filenames from directory via PHP script


Im using Angular 2+ for my project which is hosted on a ftp server. On entrance I want to load all filenames of a certain directory on my ftp server in an array and return it to Typescript. This is my code so far:

Folder structure:

-scripts
   - getMasterplan.php
-shared_plaene

TS:

    let http = new XMLHttpRequest()
    http.open('POST', Globals.PATH + '/scripts/getMasterplan.php', true)

    // http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    let resp
    http.onreadystatechange = ()=> {

        if(http.readyState == 4 && http.status == 200)
            resp = http.responseText

        console.log('resp',resp)
    }

    http.send(null)

PHP:

<?php

  session_start();

  $files = array();

  $rootDir = "../shared_plaene";

  $path = $rootDir;
  $files = scandir($path);

  echo $files;

?>

The response is undefined or "Array"

SOLVED: You cannot echo an Array


Solution

  • You need to use PHP scandir function

    Example

    <?php
    $dir = "/images/";
    
    // Sort in ascending order - this is default
    $a = scandir($dir);
    
    // Sort in descending order
    $b = scandir($dir,1);
    
    print_r($a);
    //Array ( [0] => . [1] => ..  [2] => cat.gif  [3] => dog.gif  [4] => horse.gif   [5] => myimages )
    echo ($a[4]);
    // horse.gif
    
    ?>
    

    You can't echo an Array. If you use print_r instead it will print it with the syntax as above