Page 1 of 1

Restricting file type

Posted: Sat Dec 27, 2003 2:58 am
by dakkonz
I would like to know if there is a way to restrict the file types uploaded into the server....
I wan to restrict it to mp3 and midi.... but so far the internet only give me images
thanks

Posted: Sat Dec 27, 2003 4:05 am
by Gen-ik
Can't you just check the extension of the uploaded file using stristr() ?

Code: Select all

<?php

$isMP3 = stristr($theFileName, ".mp3");

if($isMP3 !== false)
{
     // The file is an MP3 so do something here
}

?>
I think there's also a way of checking the MIME type of a file.. but I can't remember how to do it at the moment. If I remember I will let you know.

Another way would be to use JavaScript to check the file extension before the user even uploads it to the server. onsubmit="" would be a good starting point.

Posted: Sat Dec 27, 2003 11:03 am
by DuFF
Mime types for MP3's and MIDI's:

Code: Select all

.mp3    audio/mpeg3
.mp3 	audio/x-mpeg-3
.mp3 	video/mpeg
.mp3 	video/x-mpeg
.mid    audio/midi
.mid 	audio/x-mid
.mid 	audio/x-midi
.mid 	music/crescendo
.mid 	x-music/x-midi
.midi   application/x-midi
.midi   audio/midi
.midi   audio/x-mid
.midi   audio/x-midi
.midi   music/crescendo
.midi   x-music/x-midi
One way would be to compare the $_FILES['userfile']['type'] with an array of all these mimetypes (where 'userfile' is the name of the form input. Example: <input type="file" name="userfile">).

More info on uploading:
http://www.php.net/manual/en/features.file-upload.php

Posted: Sat Dec 27, 2003 11:19 am
by JAM
Gen-ik wrote:Can't you just check the extension of the uploaded file using stristr() ?

Code: Select all

$theFileName = 'Bad.mp3.FileName.exe';
Just commenting; using strstr is not recommended, as example above shows. Either substr() and/or explode() (using . and the last result in the array) would be better.

Code: Select all

$theFileName = 'Bad.mp3.FileName.bat';
$temp = explode('.',$theFileName);
echo $temp[count($temp)-1];
// bat

Posted: Sat Dec 27, 2003 11:49 am
by Gen-ik
JAM wrote:
Gen-ik wrote:Can't you just check the extension of the uploaded file using stristr() ?

Code: Select all

$theFileName = 'Bad.mp3.FileName.exe';
Just commenting; using strstr is not recommended, as example above shows. Either substr() and/or explode() (using . and the last result in the array) would be better.

Code: Select all

$theFileName = 'Bad.mp3.FileName.bat';
$temp = explode('.',$theFileName);
echo $temp[count($temp)-1];
// bat
Yeah that's a good point actually... should of thought about it myself really. :oops: