doudi8298 2013-07-14 12:40
浏览 31
已采纳

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" )
    continue;
    echo "<a href='$path/$file'>$file</a><br />"; //return the name of the track
}

// Close
closedir($dir_handle);

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";
  • 写回答

2条回答 默认 最新

  • doudou521125 2013-07-14 12:46
    关注

    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" )
        continue;
        $array[$file] = "<a href='$path/$file'>$file</a><br />"; //return the name of the track
    }
    

    sort($array);

    ... 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分