【问题标题】:Error handle not working - file upload check错误处理不起作用 - 文件上传检查
【发布时间】:2013-04-24 18:14:53
【问题描述】:

我在一个页面上有一个多张图片上传表单(最多 3 张) - 但用户可以选择根本不上传 1 张或更多张图片。当 1 个或多个留空时处理上传的脚本会给我这个错误:

“警告:copy() [function.copy]: 文件名不能为空”....

如果/当字段为空时,我尝试使用下面的代码忽略复制请求,但如果文件上传存在但它不起作用,则执行复制。有人可以告诉我为什么这不起作用或更恰当地说我需要如何以不同的方式对其进行编码吗?

表格

<form id="form1" method="post" action="processor.php" enctype="multipart/form-data">

<div>
First Profile Image  <input name="ufile[]" type="file" /><br />
Second Profile Image <input name="ufile[]" type="file" /><br />
Third Profile Image  <input name="ufile[]" type="file" /><br />
<input type="submit" name="submit" id="submit" value="Submit" />

</div>

processor.php 文件中的 PHP

$pfi1= "upload/".$_FILES['ufile']['name'][0];
$pfi2= "upload/".$_FILES['ufile']['name'][1];
$pfi3= "upload/".$_FILES['ufile']['name'][2];
if ($_FILES['ufile']['name'][0] !=="" || $_FILES['ufile']['name'][0] !==NULL) {copy($_FILES['ufile']['tmp_name'][0], $pfi1);}
if ($_FILES['ufile']['name'][1] !=="" || $_FILES['ufile']['name'][1] !==NULL) {copy($_FILES['ufile']['tmp_name'][1], $pfi2);}
if ($_FILES['ufile']['name'][2] !=="" || $_FILES['ufile']['name'][2] !==NULL) {copy($_FILES['ufile']['tmp_name'][2], $fi3);}

【问题讨论】:

    标签: php file-upload if-statement ifnull


    【解决方案1】:

    在使用复制等文件操作功能之前,您需要添加文件系统级别检查。

    先使用is_file()file_exists()检查是否可以在其上运行copy()函数

        if ($_FILES['ufile']['name'][0] !=="" 
           && $_FILES['ufile']['name'][0] !==NULL
           && file_exists("full/path/to/".$_FILES['ufile']['name'][0])
       )
       {
         copy...
       }
    

    【讨论】:

    • 你的意思是这样吗? $flag1 = file_exists($_FILES['ufile']['name'][0]);如果 ($flag1="1"); {copy($_FILES['ufile']['tmp_name'][0], $pfi1);
    • @Raidenance - 我有一个奇怪的结果,这只是短暂的工作然后停止工作,我逐个检查并重新检查,但找不到破坏它的原因。无论如何,我无法让它再次工作,并在这里找到了一条不同的路线:link
    【解决方案2】:

    在此链接的评论中使用:Multiple file upload in php 感谢:Andy Braham 对该线程的投入。

    HTML

    <input name="upload[]" type="file" multiple="multiple" />
    

    PHP

    //Loop through each file
    for($i=0; $i<count($_FILES['upload']['name']); $i++) {
      //Get the temp file path
      $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
    
      //Make sure we have a filepath
      if ($tmpFilePath != ""){
        //Setup our new file path
        $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
    
        //Upload the file into the temp dir
        if(move_uploaded_file($tmpFilePath, $newFilePath)) {
    
          //Handle other code here
    
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2014-07-10
      • 2023-03-14
      • 1970-01-01
      • 2018-10-07
      相关资源
      最近更新 更多