0

这是我的代码:

$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";
4

2 回答 2

1

在使用它之前对 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
}

排序($数组);

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

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

于 2013-07-14T12:46:02.277 回答
0

除了检查长度并在 $_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);
于 2016-10-28T06:41:08.013 回答