仅限上传到mp3

时间:2015-03-11 23:48:59

标签: php mp3 media uploading

我一直在研究一个允许人们将MP3文件上传到服务器的PHP脚本:

$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.";
    }
}
?>

在测试期间,我已经能够通过禁用限制来上传音频文件,所以我知道该程序可以工作,但我不断得到类似于下面的错误。此代码返回:

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

我尝试上传不同的mp3文件,但它们似乎都失败了。有人可以建议一种解决这些错误的方法吗?我在网上搜索了一个半小时没有运气。此外,我理解安全性是一个问题,我计划在未来的道路上开展工作,但如果有人有任何提示,我将非常感激。

1 个答案:

答案 0 :(得分:0)

更改

$fileType = pathinfo($target_file,PATHINFO_EXTENSION);

这是返回“.mp3”或类似的

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

将返回“audio / mpeg”,这是您在条件中检查的内容