在用于上传文件的代码中找不到文件索引

时间:2019-01-26 19:16:13

标签: php html

我已从w3school网站的编辑器中复制了此代码(链接:https://www.w3schools.com/php/php_file_upload.asp),并显示了此错误:

未定义索引:fileToUpload

我在其中找不到任何语法或语义问题,并且在php.ini文件中,file_uploads指令设置为on。

[
        [
            [
                [Country(state=u'state_a', city=u'city_a'), Package(filename=u'state_b', md5=u'city_b')]
            ]
        ],
 [
    [
        [
            Country(state=u'state_c', md5=u'city_c'), Country(state=u'state_d', city=u'city_d')]]]], [[[Country(state=u'state_e', city=u'city_e')]
        ]
]

2 个答案:

答案 0 :(得分:0)

将变量和其他代码放在if语句括号内,代码试图在您甚至没有上传图像之前就运行,因此isset将确保在运行任何php代码之前先上传图像。

也在您html中添加action =“ yourfilename.php " make sure its the name of your file so if its upload.php make sure the action is upload.php`

if(isset($_POST["submit"])) {
      $target_dir = "Uploads/";
      $target_file = $target_dir . basename ($_FILES["fileToUpload"]["name"]);
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename ($_FILE["fileToUpload"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    ?>

答案 1 :(得分:0)

问题是

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

运行页面时,该块也将运行。并且当您没有单击提交按钮页面时,请阅读fileToUpload并看到没有名为fileToUpload的东西,所以您会收到错误消息。

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if(isset($_POST["submit"])) {
   if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
      echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been 
uploaded.";
   } else {
    echo "Sorry, there was an error uploading your file.";
   }
 }

将此行添加到if条件

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

喜欢

if(isset($_POST["submit"])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) 
 {
    echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been 
 uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
}
}