Storm Kyleis Storm Kyleis - 1 month ago 14
PHP Question

Unsorted directory listing in PHP

This is my code:

$ost=$_GET['id']; //get the ID from the URL
$path = "audio/soundtracks/$ost"; //use the ID to select a path

// Open the folder
$dir_handle = @opendir($path) or die("Unable to open $path");

// Loop through the files
while ($file = readdir($dir_handle)) {
if($file == "." || $file == ".." || $file == "index.php" )
echo "<a href='$path/$file'>$file</a><br />"; //return the name of the track

// Close

It's purpose is to automatically list every sound track cointained in a directory, the name of which is given by the ID passed through the URL. Each track is named with the format "### - title.mp3", e.g. "101 - Overture.mp3".

It works fine, but the resulting list is sorted randomly for some reason. Is there any way to sort the tracks by title? Also, I'm pretty much a newbie with PHP, is there any security issue with the GET function? Thanks in advance.

EDIT: The GET is only used to specify the path, it's not supposed to interact with the database. Is this enough to prevent attacks?

$ost = $_GET['id'];
$bad = array("../","=","<", ">", "/","\"","`","~","'","$","%","#");
$ost = str_replace($bad, "", $ost);
$path = "audio/soundtracks/$ost";


Do some checks on GET parameter before using it. Like checking it is numeric, right lenght etc. And msyql_real_escape_String if used against db.

When looping directory, save files in array in php, with title as index. like this, then you can sort it as you please:

while ($file = readdir($dir_handle)) {
if($file == "." || $file == ".." || $file == "index.php" )
    $array[$file] = "<a href='$path/$file'>$file</a><br />"; //return the name of the track


... after this, loop and print array separately.

It is a better coding practice to first loop to arrays, and then print separatly... in my eyes. It is more flexible.