【问题标题】:.mp3 Filetype Upload.mp3 文件类型上传
【发布时间】:2010-10-21 21:51:00
【问题描述】:

我正在开发一个 PHP 上传脚本,该脚本允许上传 .mp3 文件等。我创建了一个数组,它指定了允许的文件类型,包括 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');

到目前为止,在测试中,所有指定的文件类型都已成功上传,但由于某种原因,它出现了 .mp3 错误。正如您在上面看到的,我已经包含了音频/mpeg、音频/mpeg3 和音频/x-mpeg-3,但它们似乎都没有什么不同。

有人可以提出问题所在,并指出允许上传 .mp3 所需的音频类型吗?

谢谢

更新:我用来检查文件的代码如下:

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

我得到底部 else 结果告诉我文件大小错误或扩展名不被允许。

更新 2: 我已经运行了 _FILES 数组的 print_r,希望能提供更多信息。结果是:

数组 ( [文件上传] => 数组 ( [名称] => 数组 ( [0] => 莫扎特.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
            )

    )

)

【问题讨论】:

  • 没有有问题的代码,你得到的错误对你没有多大帮助。此外,“MAX_FILE_SIZE”参数以字节为单位,因此您的限制实际上是 5MB。
  • 你能发布检查上传类型与 $permitted 数组的代码吗?

标签: php upload mp3 mime


【解决方案1】:

5MB 的限制可能是您的问题。

【讨论】:

    【解决方案2】:

    MAX_FILE_SIZE 是以字节为单位的值

    5120000 不是 500 MB。我估计是5MB。

    您还需要检查您没有超过 php.ini 文件中的“post_max_size”和“upload_max_size”变量

    其次,mp3 可以是以下任何一种 mimetypes

    • 音频/mpeg
    • 音频/x-mpeg
    • 音频/mp3
    • 音频/x-mp3
    • 音频/mpeg3
    • 音频/x-mpeg3
    • 音频/mpg
    • 音频/x-mpg
    • 音频/x-mpegaudio

    http://filext.com/file-extension/MP3

    【讨论】:

    • 好点。我现在添加了一个额外的零,它应该使它大约 48MB: // 为最大上传大小定义一个常量 define ('MAX_FILE_SIZE', 51200000);此外,我已将“post_max_size”和“upload_max_size”更改为 64MB。我已经用 phpinfo() 确认了这一点。音乐文件为 5.8MB,但在将最大大小更改为 48MB 后,我仍然收到未上传的错误消息。这只是我在 if/else 条件中设置的错误。
    • 我现在还添加了上面列出的所有 mp3 文件类型,因此数组现在显示为: $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/mp3'、'audio/x-mpeg'、'audio/x-mp3'、'audio/x-mpeg3'、'audio/x-mpg'、'audio/x-mpegaudio'、 'audio/x-mpeg-3', 'video/mpeg', 'video/mp4', 'video/quicktime', 'video/x-ms-wmv', 'application/x-rar-compressed');
    • 如果这不起作用,那么您将需要发布更多信息。编辑您的问题以包含您实际执行上传的代码(您提到的 if/else)。还可以获取一些代码来转储正在上传的文件的 mime/类型。
    • 您能否指定要包含哪些代码以及最好将其包含在何处以打印正在上传的文件的 mime/类型?
    【解决方案3】:

    这里有一些代码可以为你的错误提供一些象征意义:

    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']); 
    }
    

    如果您从最后一个 else 语句中收到错误,则很难判断究竟是什么触发了它。尝试使用类似上面的东西。 http://www.php.net/manual/en/features.file-upload.errors.php

    【讨论】:

    • 感谢您的代码,我不确定在哪里或如何包含它 - 抱歉,我将其用作学习项目。但是,我已经打印了上传的 $_FILES 数组的结果并更新了我上面的帖子。似乎它确实产生了错误= 4,但我也不确定是什么原因造成的。这是否提供了任何有用的信息,还是我应该尝试包含您的代码?如果有,还有更具体的说明吗?
    【解决方案4】:

    您永远不应假设 $_FILES[...]['type'] 中的值实际上与文件的类型匹配。客户端可以发送任意字符串,PHP 根本不检查它。见here

    您必须自己完成工作才能真正确定上传的文件类型,除非您有充分的理由根本不关心安全性(您可能根本不关心)。 PHP 默认提供fileinfo 包,它为您完成了繁重的工作。见finfo_file()

    【讨论】:

    • 感谢您的安全提示。我一直在从头开始构建它,安全性是一个大问题,所以我将阅读链接并尝试包括检查这一点。学习过程的所有部分,但感谢您指出。首先,虽然我只是在本地工作并且我是唯一的用途,但我仍在尝试使该功能正常工作,因此任何有关如何解决 .mp3 上传问题的提示也将不胜感激。有人有什么想法吗?
    【解决方案5】:
    1. 为什么不使用 in_array 而不是 foreach 循环进行类型检查?
    2. 当您上传有效文件时,您是否尝试过检查 $sizeOK 和 $typeOK 的值

    【讨论】:

      【解决方案6】:

      我怀疑你是否仍然需要这个,但我相信很多人也会面临同样的问题。这就是我所做的,它对我有用。

      PHP 代码:

      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 />');
      }
      

      您的 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>
      

      【讨论】:

        猜你喜欢
        • 2015-06-04
        • 2014-05-18
        • 2016-07-25
        • 2017-10-13
        • 1970-01-01
        • 2016-12-01
        • 2011-07-20
        • 2014-05-10
        • 2012-09-16
        相关资源
        最近更新 更多