new site();

Get array of file names in a directory (JS/PHP)


There are a lot of reasons you might want to get a list of files in a directory on the fly, including image rotators, file managers, and the like. I decided not to use this method for my own application but I figured I'd stash it here in case I need it for something else, or in case you can use it for something.

Basically, this code goes through a directory on your server and outputs the result to a JavaScript array, $fileslist in this case. As this script is not in production on any of my projects, I'm sure it could be more efficient, but it definitely works; just change the directory referenced by the $dir variable to match your own.

<script type="text/javascript" language="javascript">                            
    $fileslist = [];
    $fileslist_temp = <?php $dir = ('./images');
        $array_of_files_temp = scandir($dir);
        // shuffle($array_of_files_temp);            /* uncomment this line to randomize */
        $array_of_files= implode("\n", $array_of_files_temp);
        $array_of_files_temp = json_encode($array_of_files);
        echo ($array_of_files_temp);
    $fileslist = $fileslist_temp.split('\n');

This will not update until you refresh the page, so if you want the script to update itself you should put it in an external PHP file and call it with XMLHttpRequest, or the jQuery code I talk about in this article.