I am programming a php program that will allow users to download audio from my website.
To do this they go to www.mysite.com/downloadit.php?file=myfile.mp3 and the download of myfile.mp3 will begin immediately.
There is a problem though: I don't want people to be able to download system files. I am going to solve this by checking if $_GET['file']
contains the substrings .mp3
or .wav
. I am trying to do this with the strpos
command, but can't get it working. How would I check for more than one substring (.mp3 and .wav) in a string with strpos
? Or maybe I should use a different command? Please let me know!
Here is my code so far:
$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
}
Thanks to @DoubleSharp i now have this completed code!!!
//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");
}
?>
You can use regular expressions to test for multiple values, specifically preg_match()
. If you use the pattern \.(mp3|wav)$~i
wrapped in a delimiter (~
in this case) it will match strings that end with a literal dot .
followed by either mp3
or wav
. The $
in the pattern matches the end of the line, and the i
modifier at the end tells it to do case insensitive matching, so file.MP3
and file.mp3
will both match.
if ( preg_match("~\.(mp3|wav)$~i", $haystack) ) {
// it matches
}