Why are strings that contain [ or ] coming from $_POST transformed into an array?

Asked

Viewed 58 times

-1

I am sending data from a textarea via AJAX to PHP by the POST. method in this textarea contains some square brackets. Well, when the text of the textarea arrives in the POST, it automatically transforms the content of these brackets into another array, in which it should just return a common string. SEE:

    let textareaValue = "isso é um teste [e isso também]";
    var req = new XMLHttpRequest(); 
req.open('POST', '../controller/test.php', true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.onreadystatechange = function(){
   if (req.readyState != 4 || req.status != 200) return;
   console.log(req.responseText);
   };
req.send(textareaValue);

RESULT IN PHP:

echo $_POST;
 /* output 
array(1) {
  ["isso_é_um_teste_"]=>
  array(1) {
    ["e isso também"]=>
    string(0) ""
  }
}
*/

1 answer

2


This is because you are using application/x-www-form-urlencoded.


The application/x-www-form-urlencoded should be:

var=valor&var2=valor2 (...)

In this case PHP also understands how to array itself:

var["index"]=valor&var["outroIndex"]=outroValor

In your case you have:

isso é um teste [e isso também]

So that would be the same as doing (equivalent to isso é um teste [e isso também]=), then:

"isso é um teste" => var
[e isso também]   => ["index"]
                  => valor

There are two ways to solve the problem:


  1. Change the content-type:

Change the content-type:

req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

To:

req.setRequestHeader('Content-Type', 'text/plain');

Also, get the result in PHP using file_get_contents('php://input');, instead of $_POST.


  1. Change the body of the request to meet urlenceded

If you still want to use the application/x-www-form-urlencoded give a name to variable, such as:

 let textareaValue = "x=isso é um teste [e isso também]";

Then read the $_POST["x"].

  • sensational! That’s right there. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.