doulu3808
2019-02-02 15:07
浏览 40
已采纳

即使没有提交文件,PHP多次上传也会运行一次循环

I am trying to upload multiples files using PHP and HTML but even I set the validation in my code isset, the foreach loop runs once with empty submission.

<?php

    if (isset($_FILES['fileToUpload']))
    {

        foreach($_FILES['fileToUpload']['tmp_name'] as $key => $tmp_name)
        {
            $file_name = $key . $_FILES['fileToUpload']['name'][$key];
            $file_size = $_FILES['fileToUpload']['size'][$key];
            $file_tmp = $_FILES['fileToUpload']['tmp_name'][$key];
            $file_type = $_FILES['fileToUpload']['type'][$key];
            move_uploaded_file($file_tmp, getcwd() . "/" . time() . $file_name);
        }

        echo "Success";
    }
    else
    {
        echo "<form enctype='multipart/form-data' action='' method='POST'>";
        echo "File:<input name='fileToUpload[]' multiple='multiple' type='file'/><input type='submit' value='Upload'/>";
        echo "</form>";
    }
?>
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • doupaoyan6083 2019-02-02 15:10
    最佳回答

    You have to check the file name whether it is empty or not before run the foreach loop using PHP

    <?php
        if (isset($_FILES['fileToUpload']))
        {
            if($_FILES['fileToUpload']['tmp_name'][0] == "") {
                die("No files to upload");
            }
            else {
                // Now there are some files you can run upload method here
                foreach($_FILES['fileToUpload']['tmp_name'] as $key => $tmp_name) {}
            }
        }
    ?>
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题