Can I access duplicate post variables in PHP without '[]' in the name?

Let's say there is a form:

<form enctype="multipart/form-data" method="post">
    <input name='foo'>
    <input name='foo'>
    <input type=submit>
</form>

      

placement in my php script. How (if at all) can I find out the two values โ€‹โ€‹represented in these fields. $_POST['foo']

gives the second value, but I want both.

I understand that it can be done using <input name='foo[]'>

(which will make an $_POST['foo']

array). Due to some coding decisions, adding square brackets is not desirable (read: will require some restructuring) and it seems like there should be an easy way to do it.

If the enctype was "application / x-www-form-urlencoded" then parsing would be easy, but "multipart / form-data" was more complex and could have a 30MB file in it!

Not to mention, PHP has already parsed the post data.

Please someone tell me that PHP stores this information that it parses with $ _POST and that I can access it without parsing it again.

Thank!

+3


source to share


1 answer


You cannot access it and $_POST

will not save it. If the browser even sent it (which it should have had), the array key will be overwritten when it parses the supergalon $_POST

from the HTTP request.

This is equivalent to defining an array like:

array(
  'one' => 1,
  'two' => 2,
  'one' => 3
);

Array(2) {
  ["one"]=>
      int(3)
  ["two"]=>
      int(2)
}

      

The array icon is one

set initially, but when another value is encountered during initialization, it is immediately overwritten.

Not suitable for your situation (multipart form), but applicable to future readers:

If you have read the entire raw HTTP POST, you should be able to parse the value you want.



<?php $postdata = file_get_contents("php://input"); ?> 

      

This will give you a line like

 foo=value1&foo=value2

      

You cannot pass it to parse_str()

, though, as you will face the same array overwrite problem. You will need to parse the string to pull out another value.

Indeed, it is easier to swap them for an array with []

, if possible.

+5


source







All Articles