-1

I need to assign the list of all files of a directory (site_img) to a javascript array but not getting any luck.Can any one pls help .

i:e In the below code I want to assign the value of filename to an javascript array in each iteration of the for loop.

<?php
foreach(glob('./site_img/*.*') as $filename){
 echo $filename;
 echo "<br>";
 }

?>
user3478137
  • 9
  • 1
  • 5
  • possible duplicate of [PHP script to loop through all of the files in a directory?](http://stackoverflow.com/questions/4202175/php-script-to-loop-through-all-of-the-files-in-a-directory) – indivisible Jul 13 '14 at 18:01
  • possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – charlietfl Jul 13 '14 at 18:02

1 Answers1

0

With PHP, here is a snippet that I use on one of my sites:

<? 
        $fileList = '';
        $homePath = "a5780630"; //Dev
        $homePath = "a2092434"; //Live
        if ($handle = opendir('/home/'. $homePath .'/public_html/images/gallery/')) {

            /* This is the correct way to loop over the directory. */
            while (false !== ($file = readdir($handle))) {
                if ($file != '.' && $file != '..') {
                    $fileList = $fileList . ',' . $file;
                }
            }
            closedir($handle);
        }           
        ?>

That will give you a comma delimited string of all the files. Then in JS:

<script language="javascript">
            var listOfImages = "<?php echo $fileList; ?>" 
            listOfImages = listOfImages.split(",");
</script>
durbnpoisn
  • 4,666
  • 2
  • 16
  • 30
  • thanks a lot .but I need to assign it to an array like this img = ['file1','file2','file3'] – user3478137 Jul 13 '14 at 18:17
  • Uh, that's exactly what you will have. A Javascript array named listofImages[list]. – durbnpoisn Jul 13 '14 at 19:14
  • Cool. Sorry you got a downvote on this one. I didn't check for duplicates. I knew I had the code written already, and just posted it... I've been using that trick for years. Very convenient for the code library. – durbnpoisn Jul 14 '14 at 19:01