You want to use sort() to sort the files after you open up the directory.
I would read up on tutorials on how to display, and write to, files and directories.
I use both display and write to files and dirs, to include function modules for my software based on the the licence key.
And remember echo and print_r are you friends to see what is going on in the background while you are programming.