0

我正在编写一个允许用户从我的网站下载音频的 php 程序。
为此,他们访问www.mysite.com/downloadit.php?file=myfile.mp3,myfile.mp3 的下载将立即开始。

但是有一个问题:我不希望人们能够下载系统文件。我将通过检查是否$_GET['file']包含子字符串.mp3.wav. 我正在尝试使用strpos命令执行此操作,但无法使其正常工作。如何检查字符串中的多个子字符串(.mp3 和 .wav)strpos?或者也许我应该使用不同的命令?请告诉我!
到目前为止,这是我的代码:

$haystack=$_GET['file'];

$resulting = strpos($haystack, ".mp3");

//if found $resulting will equal 1
//if not found $resulting will equal 0

//if $resulting is less than one then it must be 0

    if($resulting < 1){
    //security breach!
    die("Unauthorized");
}

//assuming we passed the last test, everything went well, we will then continue

    else{
    //code here
}

感谢@DoubleSharp,我现在有了这个完整的代码!!!

//if it is found $resulting will not equal 0
//if it is not found $resulting will equal 0

//echo the result
//echo $resulting;

//add a line break
echo "<br/>";
//if $resulting is less than one then it must be 0
//since it is 0 it must mean that it is a breach!
if (preg_match("~\.(mp3|wav)$~i", $haystack))
{
  echo "hi nice file";
}
else
{
  die("bad file");
}
?>
4

2 回答 2

2

您可以使用正则表达式来测试多个值,特别是preg_match(). 如果您使用\.(mp3|wav)$~i包含在分隔符中的模式(~在这种情况下),它将匹配以文字点结尾的字符串,.后跟mp3or wav。模式中的$匹配行尾,最后的i修饰符告诉它进行不区分大小写的匹配,因此file.MP3file.mp3都会匹配。

if ( preg_match("~\.(mp3|wav)$~i", $haystack) ) {
    // it matches
}
于 2013-05-15T21:24:25.780 回答
2

我建议像:

$allowed = array('mp3', 'wav', 'ogg'); //whatever

$file = basename($_GET['file']);  // strip the path! (if any)

if(!preg_match("/\.(?:".implode('|', $allowed).")$/", $file){
   // Show 404, or whatever, exit
}

// Now check under trusted directories for the file,
// which should help to ensure that no system files are
// accessed since there shouldn't be any in there
于 2013-05-15T21:34:01.930 回答