简体   繁体   中英

Restricting upload to mp3 only

I have been working on a PHP script that allows people to upload MP3 files to the server:

$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $uploadOk = 1;
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 150000000000000000000000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if ($fileType != "audio/mpeg" && $fileType != "audio/mpeg3" && $fileType != "audio/mp3"
&& $fileType != "audio/x-mpeg" && $fileType != "audio/x-mp3" && $fileType != 'audio/x-mpeg3' 
&& $fileType != 'audio/x-mpg' && $fileType != "audio/x-mpegaudio" && $fileType != "audio/mpg" 
&& $fileType != "audio/x-mpg") {
     echo "Invalid Audio Type, please use MP3 Format.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

During testing I have been able to upload audio files by disabling restrictions so I do know the program works, but I keep getting similar errors as the one down below. This code returns:

Notice: Undefined index: file in /uploadsong.php on line 6
Invalid Audio Type, please use MP3 Format.Sorry, your file was not uploaded.

I have tried uploading different mp3 files and they all seem to fail. Could someone suggest a way of fixing these errors?I have searched all over the web for over an hour and a half with no luck. Also I understand security is an issue and I plan on working that out further down the road but if anyone has any tips I would be very grateful.

change

$fileType = pathinfo($target_file,PATHINFO_EXTENSION);

this is returning ".mp3" or simular

to

$fileType = $_FILES["fileToUpload"]["type"]

which will return "audio/mpeg" which is what you are checking in your condition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM