php .mp3 文件类型上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/790873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.mp3 Filetype Upload
提问by Eoin Campbell
I'm working on a PHP upload script which allows .mp3 file uploads amongst others. I've created an array which specifies permitted filetypes, including mp3s, and set a maximum upload limit of 500MB:
我正在开发一个允许 .mp3 文件上传的 PHP 上传脚本。我创建了一个数组,它指定了允许的文件类型,包括 mp3,并设置了 500MB 的最大上传限制:
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 5120000);
// create an array of permitted MIME types
$permitted = array('application/msword', 'application/pdf', 'text/plain', 'text/rtf', 'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/tiff', 'application/zip', 'audio/mpeg', 'audio/mpeg3', 'audio/x-mpeg-3', 'video/mpeg', 'video/mp4', 'video/quicktime', 'video/x-ms-wmv', 'application/x-rar-compressed');
So far in testing all specified filetypes have been successfully uploaded but for some reason it comes up with an error for .mp3. As you can see above I've included audio/mpeg, audio/mpeg3, and audio/x-mpeg-3 but none of them seem to make a difference.
到目前为止,在测试中,所有指定的文件类型都已成功上传,但由于某种原因,它出现了 .mp3 错误。正如您在上面看到的,我已经包含了 audio/mpeg、audio/mpeg3 和 audio/x-mpeg-3,但它们似乎都没有什么不同。
Can someone suggest what the problem could be and also indicate which audio type is the one needed to allow .mp3 uploads?
有人可以建议可能是什么问题,并指出允许 .mp3 上传所需的音频类型吗?
Thanks
谢谢
Update:The code I'm using to run the check on the file is as follows:
更新:我用来运行文件检查的代码如下:
// check that file is within the permitted size
if ($_FILES['file-upload']['size'][$number] > 0 || $_FILES['file-upload']['size'][$number] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of an permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['file-upload']['type'][$number]) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch($_FILES['file-upload']['error'][$number]) {
case 0:
// check if a file of the same name has been uploaded
if (!file_exists(UPLOAD_DIR.$file)) {
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['file-upload']['tmp_name'][$number], UPLOAD_DIR.$file);
}
else {
// strip the extension off the upload filename
$filetypes = array('/\.doc$/', '/\.pdf$/', '/\.txt$/', '/\.rtf$/', '/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/', '/\.tiff$/', '/\.mpeg$/', '/\.mpg$/', '/\.mp4$/', '/\.mov$/', '/\.wmv$/', '/\.zip$/', '/\.rar$/', '/\.mp3$/');
$name = preg_replace($filetypes, '', $file);
// get the position of the final period in the filename
$period = strrpos($file, '.');
// use substr() to get the filename extension
// it starts one character after the period
$filenameExtension = substr($file, $period+1);
// get the next filename
$newName = getNextFilename(UPLOAD_DIR, $name, $filenameExtension);
$success = move_uploaded_file($_FILES['file-upload']['tmp_name'][$number], UPLOAD_DIR.$newName);
}
if ($success) {
$result[] = "$file uploaded successfully";
}
else {
$result[] = "Error uploading $file. Please try again.";
}
break;
case 3:
$result[] = "Error uploading $file. Please try again.";
default:
$result[] = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['file-upload']['error'][$number] == 4) {
$result[] = 'No file selected';
}
else {
$result[] = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: doc, pdf, txt, rtf, gif, jpg, png, tiff, mpeg, mpg, mp3, mp4, mov, wmv, zip, rar.";
}
I'm getting the bottom else result telling me either the file size is wrong or the extension isn't allowed.
我得到的其他结果告诉我文件大小错误或不允许扩展名。
Update 2:I've run a print_r of the _FILES array to hopefully provide a little more info. The results are:
更新 2:我已经运行了 _FILES 数组的 print_r 以希望提供更多信息。结果是:
Array ( [file-upload] => Array ( [name] => Array ( [0] => Mozart.mp3 [1] => [2] => )
数组 ( [文件上传] => 数组 ( [名称] => 数组 ( [0] => Mozart.mp3 [1] => [2] => )
[type] => Array
(
[0] => audio/mpg
[1] =>
[2] =>
)
[tmp_name] => Array
(
[0] => /Applications/MAMP/tmp/php/phpgBtlBy
[1] =>
[2] =>
)
[error] => Array
(
[0] => 0
[1] => 4
[2] => 4
)
[size] => Array
(
[0] => 75050
[1] => 0
[2] => 0
)
)
)
)
回答by Eoin Campbell
MAX_FILE_SIZE is a value in Bytes
MAX_FILE_SIZE 是以字节为单位的值
5120000 is not 500 MB. It's 5MB by my reckoning.
5120000 不是 500 MB。据我估计,它是 5MB。
You'll also need to check that you're not exceeding the "post_max_size" and "upload_max_size" variables in your php.ini file
您还需要检查您是否没有超过 php.ini 文件中的“post_max_size”和“upload_max_size”变量
Secondly, an mp3 can be any of the following mimetypes
其次,mp3 可以是以下任何一种 mimetypes
- audio/mpeg
- audio/x-mpeg
- audio/mp3
- audio/x-mp3
- audio/mpeg3
- audio/x-mpeg3
- audio/mpg
- audio/x-mpg
- audio/x-mpegaudio
- 音频/mpeg
- 音频/x-mpeg
- 音频/mp3
- 音频/x-mp3
- 音频/mpeg3
- 音频/x-mpeg3
- 音频/mpg
- 音频/x-mpg
- 音频/x-mpegaudio
回答by chazomaticus
You should never assume the value in $_FILES[...]['type'] actually matches the type of the file. The client can send any arbitrary string, and it's not checked at all by PHP. See here.
你永远不应该假设 $_FILES[...]['type'] 中的值实际上与文件的类型匹配。客户端可以发送任意字符串,PHP 根本不检查它。见这里。
You'll have to do the work yourself to actually determine what type of file was uploaded, unless you have a good reason not to care about security at all (which you probably don't). PHP provides the fileinfopackage by default, which does the heavy lifting for you. See finfo_file().
您必须自己完成工作以确定上传的文件类型,除非您有充分的理由根本不关心安全性(您可能不关心)。PHP默认提供fileinfo包,它为您完成繁重的工作。请参阅finfo_file()。
回答by Moutaz
- why not use in_array rather than the foreach loop for type check?
- when you upload a valid file, have you tried checking the values of the $sizeOK & $typeOK
- 为什么不使用 in_array 而不是 foreach 循环进行类型检查?
- 当您上传有效文件时,您是否尝试检查 $sizeOK 和 $typeOK 的值
回答by Jay Smoke
I doubt if you still need this but am sure many will also be facing this same problem. This is what I did and it worked for me.
我怀疑你是否仍然需要这个,但我相信很多人也会面临同样的问题。这就是我所做的,它对我有用。
Php Code:
代码:
if(isset($_POST['submit'])) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
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/x-mpeg-3') {
echo('<script>alert("Error! You file is not an mp3 file. Thank You.")</script>');
} else if ($fileSize > '10485760') {
echo('<script>alert("File should not be more than 10mb")</script>');
} else if ($rep == 'Say something about your post...') {
$rep == '';
} else {
// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);
// make the random file name
$randName = md5(rand() * time());
// and now we have the unique file name for the upload file
$filePath = $uploadDir . $randName . '.' . $ext;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$sql = "INSERT INTO media SET
path = '$filePath',
size = '$fileSize',
ftype = '$fileType',
fname = '$fileName'";
if (mysql_query($sql)) {
echo('');
} else {
echo('<p style="color: #ff0000;">Error adding audio: ' . mysql_error() . '</p><br />');
}
and your html code will be;
你的 html 代码将是;
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data"">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" class="file_input" name="userfile" />
<input type="submit" value="" name="submit" id="submitStatus" class="submit" />
</form>
回答by Andy
The 5MB limit is probably your problem.
5MB 限制可能是您的问题。
回答by Nick Presta
Here is some code that will give you some symbolic meaning to your errors:
以下是一些代码,可以为您的错误提供一些象征意义:
class UploadException extends Exception {
public function __construct($code) {
$message = $this->codeToMessage($code);
parent::__construct($message, $code);
}
private function codeToMessage($code) {
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
case UPLOAD_ERR_PARTIAL:
$message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = "Missing a temporary folder";
break;
case UPLOAD_ERR_CANT_WRITE:
$message = "Failed to write file to disk";
break;
case UPLOAD_ERR_EXTENSION:
$message = "File upload stopped by extension";
break;
default:
$message = "Unknown upload error";
break;
}
return $message;
}
}
// Use
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
If you're getting an error from your last else statement, it is difficult to tell what exactly triggered it. Try using something like the above. http://www.php.net/manual/en/features.file-upload.errors.php
如果您从上一个 else 语句中得到错误,则很难判断究竟是什么触发了它。尝试使用类似上面的东西。 http://www.php.net/manual/en/features.file-upload.errors.php

