how to make PHP interpret URL GET parameters as array? - javascript

I'm trying to interpret an array url param in PHP, but it's interpreted as string instead of an array.
On client side, the url is generated with js:
URL:
let url = window.location.href.split('?')[0] //example https://www.test.com
The get parameters are added with:
const params = encodeURIComponent(JSON.stringify(array));
url += "?array="+params;
for an example array of [1010,1020,1030], the final url looks like:
https://www.test.com?array=%5B%221010%22%2C%221020%22%2C%221030%22%5D
On server side (PHP), I'm using $_GET['array'] to get those data, the output looks like:
string(22) "["1010","1020","1030"]"
It is a syntactically correct array, but interpreted as string.
I know, I could use some string manipulations to get the array I want, but is there a way, that I can get an array right from scratch?

Either decode the current parameters as JSON...
$array = json_decode($_GET['array']);
or encode the array in a way PHP understands natively...
const params = new URLSearchParams();
array.forEach((val) => {
params.append("array[]", val); // note the "[]" suffix
});
url += `?${params}`;
$array = $_GET['array'] ?? [];

Related

construct a url with input parameters from json

I am receiving a json response to construct a parameterized string in JavaScript. However I need to pass actual parameters from JavaScript on some properties e.g. custom_input has to change dynamically.
[{
"road_name_gr": "custom_input"
"town_code" : 1
}]
Then I read that json file and convert that to a url.
cql_filter = new URLSearchParams(json_file).toString();
output: town_code=1&road_name_gr=custom_input
However I have to "modify" the url to accept input.
e.g. 'town_code=1&road_name_gr=' + my_custom_input
Try this:
my_custom_input = decodeURIComponent(my_custom_input) // URI Decode
let input_params = new URLSearchParams(json_file);
input_params.set("road_name_gr", my_custom_input);
cql_filter = input_params.toString();
You have to set parameter before obtain string value.

URLSearchParams is not giving correct parameter values

I am trying to use URLSearchParams to extract the url parameters whose values are AES encrypted. But I noticed that if the value contains '+' sign, URLSearchParams is not giving proper value.
For example, if url is 'https://www.google.com/?data=a+b', URLSearcParams is giving data as 'a b'. I am using below code.
var url = new URL('https://www.google.com/?data=a+b')
url.searchParams.get('data')
Can anyone please let me know, if there is any other way to extract the url parameter values.
You must use searchParams.append() in order to set querystring params properly. I made a simple object with all keys + values and then a helper function to append the contents of the objec properly:
const url = new URL('https://www.google.com/')
const params = {
'data': 'a+b',
'moarData': 'c+d'
};
Object.entries(params).forEach(([key, val]) => url.searchParams.append(key, val));
console.log(url.searchParams.get('data'));
console.log(url.searchParams.get('moarData'));

Javascript get query string parameter values that has query string parameter in turn

I am pretty poor in regex so hoping to get some help here.
I have an url which has a query string parameters. The parameter in turn is a url which has qs parameters of itself.
For eg: my url is something like
http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true
Now when i use any of the functions to extract the whole query string parameter, i somehow get only the first one.
What i am expecting is: : /en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true
But what i get is: /en-us/products-overview/find-product/home/kitchen/2980?source=google
notice that the other two parameters (isadvertisement and organic) are missing.
my function is
function getUrlParameter(name) {
var url = 'http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true';
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(url);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
JsFiddle here:
i tried other links from SO to extract QS parameters. none of them seem to handle this scenario
The ampersands in your url are being treated as top level parameter separators. If they are part of a parameter themselves, they need to be escaped. Your escaped url would look like http://myurl.com/somepage?ref=%2Fen-us%2Fproducts-overview%2Ffind-product%2Fhome%2Fkitchen%2F2980%3Fsource%3Dgoogle%26isadvertisement%3Dfalse%26organic%3Dtrue. How you encode the url depends on where it is coming from. JS provides the encodeURIComponent() function.
Then you could use decodeURIComponent() to decode that back to the expected url. The issue is coming from having nested query parameters.
To get query parameters in general though, a built in solution using URL could be something like:
var url=new URL('...');
for (var e of url.searchParams.entries()){
console.log(e);
}

How can I obfuscate a string in JavaScript?

Basically, I want to make a game in JavaScript and allow a user to get a copy paste-able code which stores their data. In reality, this "code" is actually obfuscated JSON that can be decoded by the application later.
I don't need much security, as I am aware that if people put some effort in they can view/modify the save, and I have no interest in stopping them. I just want the average user to not be tempted and/or see unnecessary information.
Thanks in advance.
you can use base64 encoding to encode your json String. it would be faster approach.
If you with pure javascript :
var encodedData = btoa("stringToEncode");
If you are using nodejs:
base-64 encoding:
var encodedStr = new Buffer("Hello World").toString('base64')
decode to original value:
var originalString = new Buffer("SGVsbG8gV29ybGQ=", 'base64').toString('utf-8')
Well... given that there is no security concern and you only want users to see what appears to be garbled data you can "encode" all the json data
var jsonData = {"key":"value"};
// turn it into a string
var jsonString = JSON.stringify(jsonData);
// replace some letters
var awkardString = jsonString.replace(/a/g, '!Ax6'); // be carefull, you should replace a letter with a pattern that does not already exist on the string.
// encode it with some type of reversible encoding
var garbledData = encodeURI(jsonString);
// output is: %7B%22key%22:%22v!Ax6lue%22%7D
// to "decode" it do the same steps in reverse
awkardString = decodeURI(garbledData);
jsonString = awkardString.replace(/!Ax6/g, 'a'); // now you see, if '!Ax6' existed on the source string, you would loose it and get an 'a' in return. That is why the replacement should be as unique as possible
jsonData = JSON.parse(jsonString);

string to array - javascript

I am reading the plain text file in node.js using ajax call from client side.
Result :
success gives the result as below.
""[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n""
After parsing the above result :
JSON.parse(result);
"[{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}] [{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}] "
I want to change this string to array of objects,
Expected Result is array of objects:
[{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6},
{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}
]
Ajax call Code
$.ajax({
url: document.URL + "getData",
method : "GET",
success: function (result) {
var info = JSON.parse(result);
var object = JSON.parse(info);
console.log(object);
}
});
Any idea will be helpful.
That is some seriously messed-up JSON. There's an extra quote mark at each end, and ]\n[ in the middle where there should be a ,.
You really should fix your server to generate valid JSON, but if you can't, you could tweak it like this:
var res = '"[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n"';
var resfix = res.replace( /^"|"$/g, '' ).replace( ']\n[', ',' );
JSON.parse( resfix );
I changed the extra set of quotes at the very outside of your var res = string to make it a valid JavaScript string for testing.
It looks to me like you've simply got double-encoded JSON. Just run it through JSON.parse() a second time.
EDIT actually, that's not quite right - the output contains two JS arrays, with a \n separator and no enclosing array. You will have to manipulate the data a bit (looking at that now) to make it parseable a second time.
EDIT2 This appears to work, albeit that your current var res line includes an extra pair of surrounding quotes that aren't legal so in this test I've removed them:
var res = "[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n"
var out = JSON.parse(res.replace(/]\s*\[/g, ','));

Categories