When this monster is sent via POST
<input name="arrayname[index][string[name]]" value="321" />
this is what i get:
print_r($POST['arrayname']);
>> Array ( [index] => Array ( [string[name] => 321) )
Where is the secons bracket?
I can access it via:
echo $val['string[name'];
but thats just horrible.
The structure of the name should be kept if possible.
Its part of a large generic method and only in some cases theese names get generated. If its not possible to work with names like theese properly (it is but ugly like i mentioned above), i will have to change the whole form generating.
Incorrect : arrayname[index][string[name]]
Correct : arrayname[index][string][name]
You have to choose:
Let PHP convert your POST data to arrays using the square bracket syntax
Parse POST data yourself from raw post data
You just cannot have both at the same time.
<input name="arrayname[index][string][name]" value="321" />
Related
I'm serializing form data, the input names have brackets in them i.e.
when I serialize it with jquery to POST it to my php file for processing, it looks like this - test%5Btesting%5D=some input. My php file on the backend is not seeing these names when I try to grab it with:
echo $_POST['test[testing]'];
if I try just getting the info using the name test it shows it as an array. How do I tell php that the brackets are part of the field name?
<input name="test[testing]">
echo $_POST['test[testing]'];
My php file on the backend is not seeing these names when I try to grab it
PHP special cases square brackets in POST and GET data.
Access it with:
$_POST['test']['testing']
This allows you to construct a form with data that PHP will deserialize into a nested array / associative array structure that your server-side code can iterate over.
Some other form handling libraries have adopted this format, e.g. Express.js's body-parser library has an optional extended mode which supports this.
PHP has no native support for constructing a flat data structure (where $_POST['test[testing]'] would work), but you could read the raw data with:
$post_body_string = file_get_contents("php://input");
… and then write your own URL encoded form data parser.
Let's say that I have the following simple input text box:
<input type="text" name="Details[0]->Name" value="" />
Now the problem is, php translating the input name as array, and then ignore the rest name after the closing square bracket. So in print_r, it become:
Details => Array{
[0] => "Input"
}
What can I do to workaround this? Is there any unparsed $_REQUESTS?
N.B: If you noticed it, yes I am trying to use automatic input to class mapper as it has been done in Asp.net mvc.
Edit:
The additional solution requirement is that I can read raw array input from either GET, POST or multipart form requests.
For POST:
echo urldecode ( file_get_contents('php://input'));
For GET:
echo urldecode ($_SERVER['QUERY_STRING']);
Both the above give the output Details[0]->Name=testval
As for enctype='multipart/form-data', the unparsed data is not available in php. However, there is a solution of sorts given by this SO question: Get raw post data
Just replace Input with some another name like Inputcust and make new array
Details => Array{
[0] => "Inputcust"
}
and where ever you want to use again replace from Inputcust => Input
I have a form with fields and a text-area that allows any characters to be entered. I can't just submit the form, because the form is being recycled many times over, so the form values are being stored in associative arrays:
<form name='Theform'>
<input type="text" id="VISITOR_DETAILS_NAME" value="Joe">
<input type="text" id="VISITOR_DETAILS_SIZE" value="Large">
<textarea id='VISITOR_DETAILS_INFO'>
User can enter anything here including double " and single ' quotes
</textarea>
<input type="hidden" name="package" id="package" value="" />
</form>
The text-area value are stored in a JavaScript array along with the other form values:
myArray[0]['VISITOR_DETAILS_NAME'] = document.getElementById('VISITOR_DETAILS_NAME').value;
myArray[0]['VISITOR_DETAILS_SIZE'] = document.getElementById('VISITOR_DETAILS_SIZE').value;
myArray[0]['VISITOR_DETAILS_INFO'] = document.getElementById('VISITOR_DETAILS_INFO').value;
I end up with an array something like this:
{
VISITOR_DETAILS_NAME : "Joe",
VISITOR_DETAILS_SIZE : "Large",
VISITOR_DETAILS_INFO : "User can enter anything here including double " and single ' quotes"
};
I then pass this JavaScript array to the hidden form field using JSON.stringify and then POST this to PHP:
document.getElementById('package').value = JSON.stringify(myArray[0]);
Theform.submit();
(For now I'm just posting to an iframe to test that the JSON is passing the JavaScript arrays properly through POST).
When I get it on the PHP side - it seems good to go. It looks like the JSON.stringify has added the backslash to the double quote (\" ) - and now I want to store the values in MySQL. But I want to first test that I can send/reconstruct the JSON back to the javascript as an array - so I try this:
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
I get an ERROR: SyntaxError: Expected token ')' OR SyntaxError: missing ) after argument list
This is strange to me - because when I try it without POSTING - It seems to work fine like this:
document.getElementById('package').value = JSON.stringify(myArray[0]);
now if I try to just pass back the stringified value back to the array
myArray[0] = JSON.parse(document.getElementById('package').value);
- it seems to work fine - no errors
QUESTIONS:
Why am I getting this error when trying to reconstruct the ARRAY from the
POSTED JSON.stringify() value?
Do I save this JSON.stringify() value in MySQL as is?
Or do I PHP json_decode() it first?
I want to grab the form data - handle it properly - store it in MySQL and then read it back into the form when I need it.
Thanks All :)
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
Here you are are trying to convert a JSON text into an HTML representation of a JavaScript string representation of a JSON text, but you aren't doing anything to escape it for either.
If you have any ' characters in the JSON data, then they will terminate the JavaScript string.
If you have any " characters in the JSON data, then they will be represented as \", but \" is a JavaScript string representation of ". Since you don't do anything to escape the text you put in the JS string, the slash character will be consumed by the JavaScript parser and will be gone before it reached the JSON parser.
If you want to convert data for placing in a JavaScript string then you need to escape it.
However, JSON is a subset (almost) of JavaScript. So the process of converting a JSON text to a JavaScript string so it can be parsed into a JavaScript object is over-complicated. You can skip that can just go straight to:
<script>
var foo = <?php echo $json; ?>
</script>
However, since you are taking in the JSON from the client, echoing out directly will expose you to XSS attacks. In order to deal with this you should filter the data on the server.
This will:
Fail to parse any invalid JSON and so not output bad JSON (but it might output nothing, giving you a JSON syntax error, you should apply tests to see if the parse was successful and output a sensible default case if it fails).
Convert any </script> in the data to <\/script> making it safe to place in a script element (because that is how PHP's json_encode works
Such:
<!-- I don't do PHP, this is untested -->
<script>
var foo = <?php
$unsafe_json = $_POST['package'];
$data_structure = json_parse($unsafe_json);
$safe_json = json_encode($data_structure);
echo $safe_json;
?>;
</script>
Do I save this JSON.stringify() value in MySQL as is? Or do I PHP json_decode() it first?
That depends on what you intend to do with the data. In general when putting things into a database it is a good idea to extra the data from the data format and normalize it. That way you can run queries over it.
If you are only going to store the data and then retrieve it, you might be able to get away with not doing that and storing strings of JSON in the database. That loses you a lot of flexibility though and might bite you in the future.
I have strings of data in a field named content, one record may look something like:
loads of text ... [attr1] some text [attr2] more text [attr3] more text etc...
What I'm looking to do is get all the text within the square brackets; so that I can put it into a PHP array. Is this even possible with mySql?
I've seen the following post: Looking to extract data between parentheses in a string via MYSQL, but they are looking to only extract one value from between their parentheses, I have an unknown number of them. After reading that post I've though of doing something like the following;
SELECT substr(content,instr(content,"["), instr(content,"]")) as attrList from myTable
Which would grab me the following:
[attr1] some text [attr2] some more text [attr3]
and I can use PHP to strip the rest of the text out and then explode the string into an array, but is there a better way to do this just using mySql where I can retrieve something like:
[attr1][attr2][attr3]
I was thinking perhaps regex, but I see that just returns a true of false which doesn't help me a lot.
After even more research, I'm not sure it's possible in mySql, and I might need the results in string or array form depending on where I'm using them in my app.
So I've created a new method to return the list after I've got the data from the database (with a little help from this post: PHP: Capturing text between square brackets):
public function attrList($array=false)
{
preg_match_all("/\[.*?\]/",$this->content,$matches);
$params = str_replace(array('[',']'),'',$matches[0]);
return ($array===false) ? implode(', ',$params) : $params;
}
I am working on an application which, in the end, will produce a .CSV file. I have already found how to turn an array or arrays into a .CSV file, but I am having trouble figuring out the preceding step.
I have a bunch of html inputs in a form that will be sent to PHP, I am hoping to have one array consisting of all the input names (input name="example") and another array that consists of the values put into those fields by the end user.
In the end I was the CSV to be a product of both arrays. The first row being things like Height, Width, Depth, and the second row being 10 mm,20 mm,9 mm, etc etc.
I am wondering if a mixture of html classes and a foreach could be used, but I'm really not sure. Any help would be great! Thanks!!
using the square bracket notation will convert these named fields into arrays, here are a few examples
<input name="array[]">
<input name="array[]">
<input name="array[]">
<input name="array[foo]">
<input name="array[bar]">
<input name="array[0][foo]">
<input name="array[0][bar]">
<input name="array[1][foo]">
<input name="array[1][bar]">
Then to get a quick preview of your data use var_dump() or print_r()
var_dump($_REQUEST['array']);