【问题标题】:How to allow all file types for upload in php?如何允许在php中上传所有文件类型?
【发布时间】:2013-07-11 02:00:09
【问题描述】:

您好,我有一个用于允许文件上传的 php 脚本。该脚本有一个包含允许文件类型的数组。

      $fileTypes = array('jpg', 'jpeg', 'gif', 'png', 'zip', 'xlsx')

因为表单位于我的客户的登录区域后面,所以他请求允许所有文件类型,而不是仅限于阵列中的文件。虽然我已经向客户解释过最好限制文件,但他坚持要打开它。

有没有办法允许数组中的任何文件类型?

完整脚本

      $uploadDir = '/uploads/';

      // Set the allowed file extensions
      $fileTypes = array('jpg', 'jpeg', 'gif', 'png', 'zip', 'xlsx', 'cad', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'pps', 'ppsx', 'odt', 'xls', 'xlsx', '.mp3', 'm4a', 'ogg', 'wav', 'mp4', 'm4v', 'mov', 'wmv' ); // Allowed file extensions

     $verifyToken = md5('unique_salt' . $_POST['timestamp']);

    if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile   = $_FILES['Filedata']['tmp_name'];
$uploadDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
$targetFile = $uploadDir . $_FILES['Filedata']['name'];

// Validate the filetype
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array(strtolower($fileParts['extension']), $fileTypes)) {

    // Save the file
    move_uploaded_file($tempFile, $targetFile);
    echo 1;

  } else {

    // The file type wasn't allowed
    echo 'Invalid file type.';

  }
    }

【问题讨论】:

  • 是的 - 只是不要进行过滤。
  • 你能给我们看完整的脚本吗?
  • 抱歉,好的,我用脚本更新了这个

标签: php file-upload


【解决方案1】:

只是不要进行过滤。

<?php
$uploadDir = '/uploads/';

$verifyToken = md5('unique_salt' . $_POST['timestamp']);

if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
    $tempFile   = $_FILES['Filedata']['tmp_name'];
    $uploadDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
    $targetFile = $uploadDir . $_FILES['Filedata']['name'];

    // Save the file
    move_uploaded_file($tempFile, $targetFile);
    echo 1;
}

【讨论】:

    【解决方案2】:

    只需删除文件类型验证并全部上传

    //if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
    
        // Save the file
       if( move_uploaded_file($tempFile, $targetFile)){
        echo 1;
        else{
        echo 'An error occurred ';
        }
    
    //  } else {
    
        // The file type wasn't allowed
       // echo 'Invalid file type.';
    
      //}
    

    【讨论】:

      【解决方案3】:

      使用以下代码

      <?php
      $uploadDir = '/uploads/';
      
      $verifyToken = md5('unique_salt' . $_POST['timestamp']);
      
      if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
          $tempFile   = $_FILES['Filedata']['tmp_name'];
          $uploadDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
          $targetFile = $uploadDir . $_FILES['Filedata']['name'];
      
          // Save the file
          move_uploaded_file($tempFile, $targetFile);
          echo 1;
      
      }
      
      ?>
      

      【讨论】:

        猜你喜欢
        • 2011-01-29
        • 1970-01-01
        • 2018-04-04
        • 2020-12-28
        • 1970-01-01
        • 2020-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多