PHP iterate over directory files

160 views Asked by At

I have this simple code

if ($hdcss = opendir($javascript)) {

    while (false !== ($cssentry = readdir($hdcss))) {
        echo "$cssentry\n";
    }

    closedir($hdcss);
}

This will give out all files... What I want to do since I'll be getting this via Ajax is return an html string of li elements only JavaScript method is a for loop and not sure if this is done in php with opendir since this is my first time using this...

JavaScript Method:

var arry = [];

for(i=0;i<cssentry.length;i++){
    arry.push('<li>'+cssentry[i]+'</li>');
}

return arry.join(',');

If any suggestions, I'll take them.

Directory Path:

$javascript = "/cloud/'$username'/javascript/";
$css = "/cloud/'$username'/css/";
2

There are 2 answers

0
EasyBB On BEST ANSWER

Directory Path:

$javascript = "/cloud/'$username'/javascript/";
$css = "/cloud/'$username'/css/";

Directory Paths were in correct... the first forward slash is not needed

1
user3057486 On

You could use JSON format to communicate Javascript and PHP

<?php
    if ($hdcss = opendir("/tmp")) {
        $files = array();
        while (false !== ($cssentry = readdir($hdcss))) {
            // you dont want those two
            if ($cssentry != "." && $cssentry != "..") {
                $files[] = $cssentry;
            }
        }
        closedir($hdcss);
        echo json_encode($files);
    }
?>

then you will have a result in javascript

["mydir1", "mydir2", "mydir3"]

you can print array to javascript variable like this

var arry = <?php echo json_encode($files); ?>;

or fetch it using ajax