skip to Main Content

I am having issue with $_FILES array function sending through GET method. If I change the method to ‘POST’, it works but if I re-change the method to ‘GET’, it does not work.

My code is:

<body>
   <form action="?" method="GET" enctype="multipart/form-data">
      <input type="file" name="myfile" /><br>
      <input type="submit" name="submit_btn" value="Submit" />
   </form>
   <div>
      <?php
      if ($_SERVER['REQUEST_METHOD'] == 'GET') {
         print_r($_FILES);
      }
      ?>
   </div>
</body>

When I submit form, It outputs only ‘array()’ this text only not returning all values.

When I change the form method to method="POST", it works fine. Could anyone tell me please, why this is happening?

2

Answers


  1. That’s because GET requests don’t have a body, and that’s where files would go

    Login or Signup to reply.
  2. When you use a form on a webpage to send data to a server, you have a choice between using the GET or POST methods. These methods determine how the data is sent to the server.

    When you set the form method to GET, the data you fill in the form fields, including the file you select, gets added to the web address in a way. You might have noticed that the URL in the browser changes when you submit the form. However, this approach has some limitations. It’s not great for sending big chunks of data like files, and there’s a maximum limit to how much data you can send this way.

    On the other hand, when you use the POST method, the data you enter into the form is sent in a different way, sort of like a hidden package in the background. It’s more suitable for larger amounts of data, which includes files. This is why your file upload works when you change the form method to POST. The server knows how to handle this type of data and stores it properly.

    In your specific situation, when you change the form method to GET, the $_FILES array doesn’t work as expected because it’s meant to deal with data sent using the POST method. It’s kind of like trying to fit a round peg in a square hole – the GET method isn’t designed to handle file uploads the way POST does.

    If you really need to use the GET method and still want to upload files, it’s a bit tricky. You might have to get creative and encode the file data in a way that can be added to the URL, but that’s not the best way to handle files due to various issues.

    Generally, for file uploads, it’s much better to use the POST method. It ensures that your file gets safely to the server and avoids the complications of trying to fit a big thing like a file into a small space like a URL. If you’re set on using GET, you might need to think about different ways to achieve your goal, like temporarily storing the files on the server and passing references to those files through the URL.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search