我正在编写一个php程序,允许用户从我的网站下载音频。
为此,请访问 www.mysite.com/downloadit.php?file=myfile.mp3 并且 myfile.mp3 的下载将立即开始。
但是有一个问题:我不希望人们能够下载系统文件。我将通过检查$_GET['file']
是否包含子字符串.mp3
或.wav
来解决此问题。我试图用strpos
命令执行此操作,但无法使其正常工作。如何在strpos
的字符串中检查多个子字符串(.mp3和.wav)?或许我应该使用不同的命令?请告诉我!
到目前为止,这是我的代码:
$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");
}
?>
答案 0 :(得分:2)
您可以使用正则表达式来测试多个值,特别是preg_match()
。如果您使用包含在分隔符中的模式\.(mp3|wav)$~i
(在这种情况下为~
),则它将匹配以文字点.
结尾的字符串,后跟mp3
或{{ 1}}。模式中的wav
与行尾相匹配,最后的$
修饰符告诉它进行不区分大小写的匹配,因此i
和file.MP3
都匹配
file.mp3
答案 1 :(得分: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