I need to send object like php
$obj = [
array('id' => '111');
];
as POST request parameter.
I tried to use
[{struct,[{<<"id">>,<<"111">>},{<<"id">>, <<"222">>}]}]
[{struct,[{"id","111"}]}]
[{struct,[{"id":"111"}]}]
[{struct,[{"id"=>"111"}]}]
[[{"id","111"}]]
[{"id":"111"}]
[{"id"=>"111"}]
but it is wrong.
I tried to replace " by " but it's wrong too.
I don't find any examples in user manual about work with array or object. Does anyone faced with this question?
Build a query string using square brackets then URL encode it.
Example query string:
someArray[someindex_1][name]=blah&someArray[someindex_1][id]=123&someArray[someindex_2][name]=bah blah&someArray[someindex_2][id]=456
send the encoded string as the body of the post request. This should result in an array on the server like this:
print_r($_POST['someArray']);
// array(
// "someindex_1" => array(
// "name" => "blah"
// "id" => 123
// )
// "someindex_2" => array(
// "name" => "blah blah"
// "id" => 456
// )
//);
You can send an array in a POST request using the HTML element name with the square brackets "[]". An example is show below:
<input type="text" name="countries[]" value="Nigeria">
<input type="text" name="countries[]" value="Ghana">
Then in your PHP code, you can retrieve the values this way:
$countries = $_POST['countries']; //$countries is now an array of POST-ed countries
var_dump($countries);
But if what you want to send across is an Object, then you have to serialize it. You can use the code below:
$obj = get_an_object_somehow();
$encoded_obj = base64_encode(serialize($obj));
Then in your HTML form:
<input type="text" name="myObj" value="$encoded_obj">
Finally, in your form processing script, you can unserialize it as follows:
$decoded_obj = unserialize(base64_decode($obj));//get back original object
var_dump($decoded_obj);
Related
I have a json file:
$json='[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]';
and my forms post data in variable
vars="fname"=>"Ameur","lname"=>"KHIL"
"fname"=>"Marak","lname"=>"Cristo"
and I like to insert in between my json content with variable to get the final json like this:
$result='[{"Email":"myemail1#domain.com","Name":"company 1","vars":{"fname":"Ameur","lname":"KHIL","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}},{"Email":"myemail2#domain.com","Name":"Company 2","vars":{"fname":"Marak","lname":"Cristo","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}}]';
For this purpose you can use json_decode() to parse the JSON-String to a PHP-Object. Then you just set a new value vars to the given form values.
Parsing the JSON-String
$json = json_decode('[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]');
Adding the new vars value and removing the additional ones. This is just for the first entry but you can do the same for the other entry or even iterate through the array for multiple entries
$json[0]->vars = ["fname" => "Marak", "lname" => "Cristo", "Tel1" => $json[0]->Tel1,"Adresse" => $json[0]->Adresse];
unset($json[0]->Tel1);
unset($json[0]->Adresse);
And getting your result in a JSON-String
$result = json_encode($json);
I have a problem when uploading a list of filenames to php. If the filename contains ] it will break the array decoding in PHP.
It can also be reproduced using $_GET as shown here.
What i want this to be decoded as is:
Array
(
[a] => Array
(
[b[]] => c
)
)
The goal is having a key in an array also containing the ] character
index.php?a[b[]]=c
Gives me this:
Array
(
[a] => Array
(
[b[] => c
)
)
Encoding them gives same problem
index.php?a[b%5B%5D]=c
Gives me this:
Array
(
[a] => Array
(
[b[] => c
)
)
Double encode it does not work either
index.php?a[b%255B%255D]=c
Gives me this:
Array
(
[a] => Array
(
[b%5B%5D] => c
)
)
Is it possible to encode this so PHP will decode it into a array with keys with the string that contains
Referencing my comment. You've put your focus on the wrong side of the table. It's not the handling of incoming information that is the problem, it's your client side submission of the data that isn't correctly passing through data. The brackets are UNSAFE characters to submit through to an endpoint and the client that is submitting this information is where you need to make the changes, not the backend handling the data.
Read up on the safe and unsafe characters in URL's here:
Stop using unsafe characters in URL's
Brackets are used to define nested list data and the way you are attempting to use it breaks that logic, you will have to change the way your frontend (or whatever is doing the HTTP request) encodes that data.
I don't know about your file upload and you need [ - character in filename or not, but problem with the $_GET array I can sloved so:
<? dump($_GET['a']); // Array([b[] => c)
$arr = [];
foreach ($_GET['a'] as $key => &$value) {
$vl = str_replace('[', '', $key);
dump($key); // b[
dump($vl); // b
$arr[$vl] = $value;
}
dump($arr); // Array([b] => c)
?>
Hope it helps you.
If you write a small script, you can ask PHP what it prefers:
<?php
$c = 0;
$data = array(
"a" => array(
"b[]" => $c
)
);
echo "<pre>";
var_export($data);
echo "\r\na[b[]]=c Encoded: " . urlencode("a[b[]]=c");
echo "</pre>";
?>
Results
array (
'a' =>
array (
'b[]' => 0,
),
)
a[b[]]=c Encoded: a%5Bb%5B%5D%5D%3Dc
Update
I wrote the following code just to see how the browser is encoding it:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(function(){
$("form").submit(function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
<label for "a">a[b[]] = </label>
<input type="text" name="a[b[]]" id="a" value="c" />
<br />
<button type="submit">
Go
</button>
</form>
</body>
</html>
When I click Go, I see the following in console:
a%5Bb%5B%5D%5D=c
When I then run it through urldecode():
<?php
echo urldecode("a%5Bb%5B%5D%5D=c");
?>
I see the following results:
a[b[]]=c
So it looks like you do not need to encode the = symbol, but you do want to encode [ and ] properly: %5B and %5D respectively.
So if you want to use:
index.php?a[b[]]=c
I would advise:
index.php?a%5Bb%5B%5D%5D=c
Hope that helps.
I have list of items, after selecting them and pressing a submit button
there's kind of a query in the url bar as such :
adrese-id=7&food-id=1&food-id=2&food-id=3&food-id=4
Trying to get all of the food IDs in an array but no luck so far, tried doing:
$ids = $_GET['food-id'];
but that just has the last value, which is 4...
How do I get those values in an array?
You have to name your field to indicate it's an "array". So, instead of food-id, append brackets to the end to make it food-id[]
For example:
<input type="checkbox" name="food-id[]" value="1"> Pizza
<input type="checkbox" name="food-id[]" value="2"> Cheese
<input type="checkbox" name="food-id[]" value="3"> Pepperonis
Accessing it in PHP will be the same, $_GET['food-id'] (but it will be an array this time).
In php the $_GET array has $key => $value pairs. The 'food-id' in this case is the $key.
Because all your values (1,2,3,4) have the same key: 'food-id' the array looks like this:
$_GET = [
'food-id' => 1,
'food-id' => 2,
'food-id' => 3,
'food-id' => 4,
]
This will always be parsed with the last $key => $value pair being used:
$_GET = [
'food-id' => 4
]
The solution to this is always using unique keys in your arrays.
You really need to provide the HTML fragment that generates the values. However if you look at your GET request the values for food-id are not being submitted as an array which is presumably what you want. Your GET request should look more like:
adrese-id=7&food-id[]=1&food-id[]=2&food-id[]=3&food-id[]=4
which should give you a clue as to how your HTML form values should be named.
I am trying to fix a bit of code and display an image that is set with a custom metabox. I have found the saved data in wp_postmeta and it looks like the data is saved as a string but I can see an obvious key value pair.
When I use the following code...
$imgVar = get_post_meta($post->ID, 'attachments', true);
$testing4 = $imgVar;
var_dump($testing4);
...I get the following output...
string(101) "{"my_item":[{"id":"653","fields":{"title":"mytitle","caption":"test this out"}}]}"
... this looks like it is telling me that the output is a string with 101 characters but I see key values and an array.
what I would like to have output is, or what it seems it should be...
array[0](
"my_item" => array(
"id" => "653",
"fields" => array(
"title" =>"mytitle",
"caption" => "test this out"
),
)
),
can someone explain what is being output for this newb :), and if it is possible to turn what is being output into a regular array. Or if I can access the key value "id => 653" without switching the output.
Thanks.
The output-string is probably serialized (easier for Wordpress to store data more efficient).
Try:
<?php maybe_unserialize( $original ) ?>
If you want to know more about this look at: http://codex.wordpress.org/Function_Reference/maybe_unserialize
$var = json_decode($testing4);
Format output with <pre> tags
echo '<pre>' . var_dump($testing4) . '</pre>';
how to send array through url in PHP?
I have an array of product ids i want to use these id through url because this is the osCommerce needs it in which i am working in, how can i do it?
Generally osCommerce asks for the single product insertion which in turn gives me back a product id which i pass into the url and get it in shopping cart where i am shown this added product, but now i have multiple products added in first page with different generated product ids and i have to display these products the same way they are displayed in genaral, for which i will need all these generated ids here in url
Your looking for http_build_query().
Example from php.net:
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data);
// foo=bar&baz=boom&cow=milk&php=hypertext+processor
echo http_build_query($data, '', '&');
// foo=bar&baz=boom&cow=milk&php=hypertext+processor
?arr[]=abc&arr[]=pqr&arr[]=xyz&arr[]=xxx
well what i would do is json_encode(php json) the array and assign that to a variable in php. you can then urlencode the variable to send it via the url. On the other end you can json_decode. Do look up for json if you are not aware of it. its very powerful and useful though.
You can either serialize() it or send it as ?a[]=1&a[]=val2&someOtherArg=val. This will give a $_GET array like:
array(
'a' => array(
0 => '1',
1 => 'val2',
),
'someOtherArg' => 'val'
)
Do note, however, that you should probably keep your entire query below ~2k characters. (more)
If you are POST-ing data, then name your fields with PHP array-style syntax:
<input type="text" name="myArray[]" value="A">
<input type="text" name="myArray[]" value="B">
<input type="text" name="myArray[]" value="C">
If you want to pass the data in a GET request, you can separate the data and split it server side using explode:
page.php?myData=A,B,C,D
...
$myArray = explode(',', $_POST['myData']);
It should be sufficient to encode them like this:
http://your.url/page.php?myArray[0]=val1&myArray[1]=val2
If you already have the product IDs in an array, then you can use the http_build_query() function, which will encode the array like thus:
http://www.example.com/?pid[]=1&pid[]=2&pid[]=3 ...
Hope that helps.