Search code examples
phpfile-upload

$_Files is empty in php 8 upload


I’m trying to learn a little bit of php and html. Today I did my first fileupload. But the array $_FILES seams to be empty / null. If I try to access it, I get an error, that my key is not found.

The apache log seams ok:

192.168.1.79 - - [26/May/2021:13:36:13 +0000] "GET /buchdemo/hochladen.php?upfile=test.txt&hochladen=Senden HTTP/1.1" 200 565 "http://192.168.1.96/buchdemo/hochladen.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15"

But the PHP Code doesn’t enter the first if

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
   
    
    <body>
         <h2> Upload </h2>
          <?php
          if (!empty($_FILES))
          {
              if (count($_FILES)>0)
                {
                    for ($i=0; $i<count($_FILES); $i++)
                    {
                        echo $i ."<br>"; 
                        echo $_FILES[$i];
                    }
                }
                else
                {
                    echo "keine Daten";
                }

                if ($_FILES["upfile"]["size"]>0)
                {
                    echo '$_FILES["upfile"]["tmp_name"]';
                    $info = $_FILES["upfile"]["tmp_name"];
                    copy($_FILES["upfile"]["tmp_name"], $info);
                }
          }
        
        ?>
         <form action="hochladen.php" action="post" enctype="multipart/form-data">
             <p> <input name="upfile" type="file"></p>
             <p> <input type="submit" name="hochladen"></p><br>
         </form>
       
    </body>
</html>

Solution

  • As Musa has pointed out, you need to set your form method to POST. Now you are setting the action to post.

    • The action attribute defines where the form-data is sent when the form is submitted.

    • The method attribute defines how the form-data is sent.

    To upload files in PHP you need to use either the POST or PUT method (https://www.php.net/manual/en/features.file-upload.post-method.php)

    So the code should be:

    <form action="hochladen.php" method="post" enctype="multipart/form-data">
       <p> <input name="upfile" type="file"></p>
       <p> <input type="submit" name="hochladen"></p><br>
    </form>