欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php上传文件常见问题总结

程序员文章站 2023-10-30 16:36:16
把php上传文件时经常碰到的几个问题总结一下吧,以后用到时不用再去找了。 1.先做个最简单的上传文件 复制代码 代码如下:   &...

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

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

复制代码 代码如下:

 <html>
 <head>
 <meta http-equiv="content-type" content="text/html; charset=utf-8">
 </head>
 <body>
 <form action="upload_file.php" method="post"
 enctype="multipart/form-data">
 <label for="file">filename:</label>
 <input type="file" name="file" id="file" />
 <br />
 <input type="submit" name="submit" value="submit" />
 </form>
 </body>
 </html>

复制代码 代码如下:

<?php
if (($_files["file"]["size"] < 20000)
  {
  if ($_files["file"]["error"] > 0)
    {
    echo "return code: " . $_files["file"]["error"] . "<br />";
    }
  else
    {
    echo "upload: " . $_files["file"]["name"] . "<br />";
    echo "type: " . $_files["file"]["type"] . "<br />";
    echo "size: " . ($_files["file"]["size"] / 1024) . " kb<br />";
    echo "temp file: " . $_files["file"]["tmp_name"] . "<br />";
    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_length; $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.情景三:多文件上传

复制代码 代码如下:

 <form action="" method="post" enctype="multipart/form-data">
 <p>pictures:
 <input type="file" name="pictures[]" />
 <input type="file" name="pictures[]" />
 <input type="file" name="pictures[]" />
 <input type="submit" value="send" />
 </p>
 </form>

复制代码 代码如下:

 <?php
 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. 有的时候:需要配置服务器修改最大上传文件大小

首先,在表单上

<input type="hidden" name="max_file_size" value="字节" />
可以限制上传文件大小(可以被绕过)。

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

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;
  }

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