1

我正在开发一个 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.";
        }

我得到底部的其他结果,告诉我文件大小错误或不允许扩展名。

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

数组 ( [file-upload] => 数组 ( [name] => 数组 ( [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
            )

    )

)

4

6 回答 6

10

MAX_FILE_SIZE 是以字节为单位的值

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

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

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

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

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

于 2009-04-26T14:02:50.783 回答
1

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

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

于 2009-04-26T16:43:36.060 回答
1
  1. 为什么不使用 in_array 而不是 foreach 循环进行类型检查?
  2. 当您上传有效文件时,您是否尝试过检查 $sizeOK 和 $typeOK 的值
于 2009-04-26T23:30:09.720 回答
1

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

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>
于 2012-06-01T19:09:36.863 回答
0

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

于 2009-04-26T14:01:43.237 回答
0

这是一些代码,可以为您的错误提供一些象征意义:

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

于 2009-04-26T16:21:02.713 回答