Parsing multipart form data

DashRantic picture DashRantic · Jul 2, 2009 · Viewed 80k times · Source

I'm trying to put together a HTML POST-ed form that has two fields--a file upload, and a text field. Since the form has a type multipart/form-data for the file upload, I can't get at the text field through the normal PHP $_POST variable. So how can I get at the text field in the form with PHP?

As per requested, here's some code, basically taken directly from Andrew:

<html>
    <body>
        <form action="test2.php" method="post" enctype="multipart/form-data">
            Name: <input type="text" name="imageName" />
            Image: <input type="file" name="image" />
            <input type="submit" value="submit" />
        </form>
    </body>
</html>

<?php
  echo $_POST['imageName'];
  echo "<pre>";
  echo var_dump($_FILES['image']);
  echo "</pre>";
?>

That's the entire test file. If I remove the enctype, I can get the POST-ed data, but not the file of course. With the enctype as multipart/form-data, I can get the file, but nothing from the POST-ed data.

Here's the output with the enctype:

array(5) {
  ["name"]=>
  string(34) "testing.png"
  ["type"]=>
  string(0) ""
  ["tmp_name"]=>
  string(0) ""
  ["error"]=>
  int(1)
  ["size"]=>
  int(0)
}

Without:

testing

NULL

Same exact input both times.

Answer

Sampson picture Sampson · Jul 2, 2009

File uploads come through $_FILES. Everything else comes through $_POST (assuming of course your HTML form had its method attribute set to "post").