search
HomeBackend DevelopmentPHP Tutorialphp上传文件常见问题总结_php实例

把php上传文件时经常碰到的几个问题总结一下吧,以后用到时不用再去找了。

1.先做个最简单的上传文件

复制代码 代码如下:

 
 
 
 
 
 
 enctype="multipart/form-data">
 
 
 

 
 
 
 

复制代码 代码如下:

if (($_FILES["file"]["size"]   {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "
";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "
";
    echo "Type: " . $_FILES["file"]["type"] . "
";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";
    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

2.然后了解超级全局变量$_FILES的值

复制代码 代码如下:

$_FILES['userfile']['name']
$_FILES['userfile']['type']
$_FILES['userfile']['size']
$_FILES['userfile']['tmp_name']
$_FILES['userfile']['error']

其中,$_FILES['userfile']['error']的所有值:

UPLOAD_ERR_OK 其值为 0,没有错误发生,文件上传成功。

UPLOAD_ERR_INI_SIZE 其值为 1,上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。

UPLOAD_ERR_FORM_SIZE 其值为 2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。

UPLOAD_ERR_PARTIAL 其值为 3,文件只有部分被上传。

UPLOAD_ERR_NO_FILE 其值为 4,没有文件被上传。

UPLOAD_ERR_NO_TMP_DIR 其值为 6,找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。

UPLOAD_ERR_CANT_WRITE 其值为 7,文件写入失败。PHP 5.1.0 引进。

3.很多情况:需要严格判断上传文件类型

     我们知道使用$_FILES['userfile']['type']判断上传文件类型是一个很不明智的做法,因为该判断依据是文件的后缀名,任何人都可以将一个mp3文件的后缀改成jpg从而伪装成图片进行上传,因此php官方建议使用php的扩展php_fileinfo来判断文件的mime,开启拓展的方法百度一下有很多,win和linux略有不同。

4.情景一:上传文件重名后自动重命名

复制代码 代码如下:

if (file_exists("./upload/" . $_FILES["file"]["name"])) 
{   
   do{ 
       $suffix =""; 
       $suffix_length = 4; 
       $str = "0123456789abcdefghijklmnopqrstuvwxyz"; 
       $len = strlen($str)-1;
       //文件名后追加4个随机字符 
       for($i=0 ; $i           $suffix .= $str[rand(0,$len)]; 
       } 
       $upload_filename = $_FILES['file']['name'];                                           
       $filename = substr($upload_filename,0,strrpos($upload_filename,".")).$suffix.".".substr($upload_filename,strrpos($_FILES["file"]["name"],".")+1);
   }while(file_exists("./upload/".$filename)); 
       move_uploaded_file($_FILES["file"]["tmp_name"],"./upload/" . $filename); 
}else{ 
       move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);  

5.情景二:根据日期分目录上传文件

复制代码 代码如下:

$structure = './'.date("Y").'/'.date("m").'/'.date("d").'/';
if (!mkdir($structure, 0777, true)) {
    die('Failed to create folders...');
}
move_uploaded_file($_FILES["file"]["tmp_name"],$structure . $_FILES["file"]["name"]);

6.情景三:多文件上传

复制代码 代码如下:

 

 

Pictures:
 
 
 
 
 


 

复制代码 代码如下:

   foreach ($_FILES["pictures"]["error"] as $key => $error) {
     if ($error == UPLOAD_ERR_OK) {
         $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
         $name = $_FILES["pictures"]["name"][$key];
         move_uploaded_file($tmp_name, "data/$name");
     }
 }
 ?>

有的情况下多文件的这种变量结构并不好用:

复制代码 代码如下:

array(1) {
    ["upload"]=>array(2) {
        ["name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
    }
}

很多情况下我们需要的是类似这样的结构

复制代码 代码如下:

array(1) {
    ["upload"]=>array(2) {
        [0]=>array(2) {
            ["name"]=>string(9)"file0.txt"
            ["type"]=>string(10)"text/plain"
        },
        [1]=>array(2) {
            ["name"]=>string(9)"file1.txt"
            ["type"]=>string(10)"text/html"
        }
}
}

使用下面的函数就能轻松转化结构

复制代码 代码如下:

 function diverse_array($vector) {
     $result = array();
     foreach($vector as $key1 => $value1)
         foreach($value1 as $key2 => $value2)
             $result[$key2][$key1] = $value2;
     return $result;
 }
 $upload = diverse_array($_FILES["upload"]);

7. 有的时候:需要配置服务器修改最大上传文件大小

首先,在表单上


可以限制上传文件大小(可以被绕过)。

然后在服务器上也需要调整一下配置

php.ini:

max_execution_time = 30 每个脚本运行的最长时间,单位秒
max_input_time = 60,每个脚本可以消耗的时间,单位也是秒
memory_limit = 128M,这个是脚本运行最大消耗的内存
post_max_size = 8M,表单提交最大数据为 8M,此项不是限制上传单个文件的大小,而是针对整个表单的提交数据进行限制的。
upload_max_filesize = 2M ,上载文件的最大许可大小

nginx:

复制代码 代码如下:

 location / {
     root   html;
     index  index.html index.htm;
     client_max_body_size    1000m;
  }

以上就是常见的问题的处理方法了,希望大家能够喜欢。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)