【问题标题】:Unsorted directory listing in PHPPHP中未排序的目录列表
【发布时间】:2013-07-12 10:40:28
【问题描述】:

这是我的代码:

$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);

其目的是自动列出目录中包含的每个音轨,其名称由通过 URL 传递的 ID 给出。每首曲目的命名格式为“### - title.mp3”,例如“101 - Overture.mp3”。

它工作正常,但由于某种原因,结果列表是随机排序的。有没有办法按标题对曲目进行排序?另外,我几乎是 PHP 的新手,GET 函数有什么安全问题吗?提前致谢。

编辑:GET 仅用于指定路径,它不应该与数据库交互。这足以防止攻击吗?

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

【问题讨论】:

  • 先将数据放入数组,再排序。然后输出数组的结果。是的,在路径中使用获取内容存在安全问题。如果我传入 ../../../../ 而不是整数 id 会发生什么?
  • 只需像这样在 GET 上使用 basename 函数:basename($_GET['id'])

标签: php list sorting directory


【解决方案1】:

除了在 $_GET 上检查长度和使用转义字符串安全措施外,您还可以将 id 编码和解码到 URL 并在使用之前对其进行解码。

//before putting into URL

 $id = $rows["id"];
$id = base64_encode($id);
<a href="yourUrl.php?id='$id'"

//in yourUrl.php

$id = $_GET['id'];
     $id =  base64_decode($id);

【讨论】:

    【解决方案2】:

    在使用之前对 GET 参数做一些检查。就像检查它是数字,正确的长度等。如果对 db 使用 msyql_real_escape_String。

    循环目录时,将文件保存在php中的数组中,以标题为索引。像这样,那么你可以随意排序:

    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
    }
    

    排序($array);

    ...之后,分别循环和打印数组。

    在我看来,首先循环到数组,然后单独打印是一种更好的编码实践。它更灵活。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-25
      • 2015-04-27
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多