How to pass json encode into cookie in PHP - javascript

When im check JSON encode with print_r it look fine => {"expiry":1636191448,"auth":true}
Then im try to store it inside cookie,
but it turn into like this when i see it in browser cookies value => %7B%22expiry%22%3A1636191866%2C%22auth%22%3Atrue%7D
Can anyone tell me how to fix it. Im not use this for permission system, but for other thing like read it in javascript but i got error when try to parse it
Uncaught SyntaxError: Unexpected token % in JSON at position 0
at JSON.parse ()
.
This are the line of code in my php file
if (Cookie::exists(Config::get('client/cookie_name'))) {
$client = json_decode(Cookie::get(Config::get('client/cookie_name')), true);
$expiry = $client['expiry'];
} else {
$client = array (
'expiry' => time() + Config::get('client/cookie_expiry')
);
}
$client['auth'] = true;
$client = json_encode($client);
Cookie::update(Config::get('client/cookie_name'), $client, $expiry);

Cookies are often URL-encoded (but sometimes different encodings are used). Since this isn't really standardized and by spec there is only a handful of characters that must be encoded somehow (not specified how), different systems may take different routes in handling cookie encoding, and therefore reading cookies set by one system using another system can cause issues like these.
In your case, you can call decodeURIComponent on the value first:
const json = decodeURIComponent(encodedCookieValue)
const data = JSON.parse(json)
Further reading: Should cookie values be URL encoded?

Related

How I can fetch textarea data to node js

I cannot send data of <textarea> to node js, Node js don't see the my sent data.
For Fetch data to Node Js
continueBtn.addEventListener("click", async () => {
console.log(myMsg.value)
console.log(typeof(myMsg.value))
const req = await fetch("/sendmsg", {method: "POST",body: myMsg.value}) ;
console.log("Fetched")
})
For get data in Node js
const {userMessage} = Object.keys(req.body)
You are passing a string to body. Since you aren't overriding it, it will be given a text/plain content-type.
On the server you expect req.body to contain an object.
You haven't shown us what, if any, body parsing middlewares you have configured in your server side code, but none of the common ones will convert something that is text/plain into an object.
You should:
Make sure that you have a body parsing middleware configured
Encode the data you are passing to body (e.g. with URLSearchParams) so it has name=value pairs instead of being a plain string.
If you end up passing a string (e.g. if you pass a string of JSON instead of a URLSearchParams object) then you'll also need to set a Content-Type request header that matches your data format.
"const {userMessage} = Object.keys(req.body)"
I don't see why you'd be expecting to have a userMessage key in your body object with the code you pasted. It's possible the data is being passed properly, but you are trying to access the wrong key. I would try logging in your server code to debug the response format as a first step:
console.log(JSON.stringify(req.body))
Let me know if that gets you enough help to move forward, and I can circle back here if not.

Remove quotes when reading from sessionStorage and sending to php using jquery

I'm storing different values in the sessionStorage during a longer process. At the end i want to read all the data and send it to my php backend using ajax. The problem is that php seems to take every value including quotes. Here is what i got:
// Reading data from storage
var imgb = sessionStorage.getItem("img_b_id");
....
// perpare data
var oData = {
imgb: imgb,
...
};
// Sending data
$.post( "../php/direct/create.php", oData).done(function(data) {
if(data==true) {
window.open("step5.php", "_self");
} else {
alert("Error: " + data.toString());
}
});
This is working perfectly fine. However, php will read the value of imbg with quotes. Example:
echo $_POST['imgb'];
/* Returns "asd" instead of asd
The image below shows that my data is stored without the quotes (chrome sessionstorage screenshot)
Do you have any suggestions on how to solve this. I currently replace the quotes, but I'd love to fix this problem at it's root...
I have tried your code ( with Firefox and Chrome ) and
echo $_POST['imgb'];
Print the string without quotes.
Consider that even if you set a number in the session storage, for example
sessionStorage.setItem("img_b_id", 100);
The value is received at server by PHP as a string so you can convert it with PHP functions intval(), floatval() etc.
http://php.net/manual/en/function.intval.php

JWT on PHP side

I'm working on a AngularJS / Phonegap / PHP (Zend) project.
I want the users to login via JWT. (this seems the best options since cookies not work). I've found a tutorial to manage it on the angular side
I went googling a lot and found out that google uses the https://github.com/luciferous/jwt version. Also I found a newer one based on that from firebase ( https://github.com/firebase/php-jwt )
(1) Which one should I use?
I'm using the luciferous now and when I create a token via:
$ENV_var = "whatever":
$token = encode("id: 5", $ENV_var);
It returns: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ImlkOiA1Ig.KtG-rOleZwiDhbMnaLI1vIOczPYUM2Az1KfIeygJ7E0 which is unvalid here but valid if I decode it with the same script.
(2) Why is this? is this because jwt.io is made with/by Auth0?
(3)Also I don't get when/why I should use the "sign method" instead of encode (below: from github luciferous)
public static function sign($msg, $key, $method = 'HS256')
{
$methods = array(
'HS256' => 'sha256',
'HS384' => 'sha384',
'HS512' => 'sha512',
);
if (empty($methods[$method])) {
throw new DomainException('Algorithm not supported');
}
return hash_hmac($methods[$method], $msg, $key, true);
}
1) I would recommend using the firebase implementation, since it is maintained more and has composer support.
The payload that is passed into the encode method should be an array of "claims" see here e.g.
$payload = array('sub' => 1, 'iss' => 'example.com');
$secret = 'someSecretKey';
$token = JWT::encode($payload, $secret);
2) because the token you are generating is not based on an array or contain any required claims.
3) you should generally use the encode/decode methods as they will call sign internally
Ad 1. Both are fine to use, however the second has got better documentation. I personally prefer to work with https://github.com/firebase/php-jwt.
You said that JWT generated is not valid. I have tested it and it worked (it got decoded correctly), just make sure to use correct algorithm "HS256" and your secret.
Ad 2. This question is not clear, can you please clarify?
Ad 3. Encode method of that class calls sign. You don't have to call sign yourself, just encode.

JSON response from Google Analytics api

I am using the google-api-ruby-client to get a response from the Google Analytics api, which is successful, the one thing I am a little confused with though is the response object. I would like to know how to drill down into specific keys and their values or even parse the response to make it more understandable.
Below is what I believe is the relevant part of the JSON response
"{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"query\":{\"start-date\":\"2014-01-01\",\"end-date\":\"2014-07-22\",\"ids\":\"ga:88893966\",\"dimensions\":\"ga:pagePath\",\"metrics\":[\"ga:pageviews\"],\"filters\":\"ga:pagePath==/\",\"start-index\":1,\"max-results\":1000},\"itemsPerPage\":1000,\"totalResults\":1,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"profileInfo\":{\"profileId\":\"88893966\",\"accountId\":\"53082810\",\"webPropertyId\":\"UA-53082810-1\",\"internalWebPropertyId\":\"85713348\",\"profileName\":\"All Web Site Data\",\"tableId\":\"ga:88893966\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:pagePath\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:pageviews\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:pageviews\":\"8\"},\"rows\":[[\"/\",\"8\"]]}"
which is obtained from
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(2014,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/'
})
puts ap(result)
Also when I do:
puts ap(result.data.rows.inspect)
#returns
"[[\"/\", \"8\"]]"
and when i try
response = JSON.parse(result.data.totalsForAllResults)
puts ap(response)
# returns error
TypeError: no implicit conversion of #<Class:0x00000001950550> into String
I am wondering how I can format the response without the backslashes and how I would say get the total page views?
Your syntax is off.
If result is simply a string that is a json object, which it looks like above, what you want is:
response = JSON.parse(result)
ap response["totalsForAllResults"]["ga:pageviews"]
Looking at the google-api-ruby-client the result.data returns an object if parseable from api schema, a hash if you pass the media type "application/json", or a string otherwise. So you need to determine if you are accessing the response data as an object or a Hash. My example above parses the raw string into a ruby hash.
tl;dr; there are multiple ways to attain the data you want.
Yes, your syntax is off. It should look something like this.
https://www.googleapis.com/analytics/v3/data/ga?ids=ga:_____&dimensions=ga:date&metrics=ga:impressions,ga:adClicks,ga:adCost&start-date=2015-10-13&end-date=today
BaseUrl, id, metrics, start-date and end-date are required. And don't forget to insert the access_token as well.

How can I send foreign characters with YUI io (XMLHttpRequest)

I'm using YUI io to post data to my server. I have some problems sending foreign characters like æ ø å.
First case: a form is posted to the server
Y.io(url, {
method: 'POST',
form: {
id: 'myform',
useDisabled: true
}
});
This will post the content of the form to the server. If I have a field named "test1" containing "æøå", then on the server I'll see REQUEST_CONTENT="test1=%C3%A6%C3%B8%C3%A5". This can be easily decode with a urldecode function, NO PROBLEM, but...
Second case: data is posted this way:
Y.io(uri, {
data : '{"test1":"æøå"}'),
method : "POST"
});
Now I see this on the server REQUEST_CONTENT="{"test1":"├ª├©├Ñ"}". How can I decode that? And why is it send like that?
I know I can use encodeURIComponent() to encode the string before sending it. But the io request is actually part of a Model Sync operation, so I'm not calling io directly. I'm doing something like this:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {....});
var user = new Y.User();
user.set('test1', 'æøå');
user.save();
So it doesn't make sense to encode/decode everytime I set/read the attribute.
Also I have tried to set charset=utf-8 in the request header, but that didn't change anything.
EDIT
I have done some more debugging in chrome and the request is created with this line of code:
transaction.c.send(data);
transaction.c is the xmlhttprequest and (using chrome debugger) I can see the data is "{"test1":"æøå"}"
When the above line of code is executed, a pending network entry is shown (under the network tab in chrome debugger). Request payload displays {"test1":"├ª├©├Ñ"}
Headers are:
Accept:application/json
Content-Type:application/json; charset=UTF-8
ModelSync.REST has a serialize method that decides how the data in the model is turned into a string before passing it to Y.io. By default it uses JSON.stringify() which returns what you're seeing. You can decode it in the server using JSON. By your mention of urldecode I guess you're using PHP in the server. In that case you can use json_decode which will give you an associative array. If I'm not mistaken (I haven't used PHP in a while), it should go something like this:
$data = json_decode($HTTP_RAW_POST_DATA, true);
/*
array(1) {
["test1"] => "æøå"
}
*/
Another option would be for you to override the serialize method in your User model. serialize is a method used by ModelSync.REST to turn the data into a string before sending it through IO. You can replace it with a method that turns the data in the model into a regular query string using the querystring module:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {
serialize: function () {
return Y.QueryString.stringify(this.toJSON());
}
});
Finally, ModelSync.REST assumes you'll be using JSON so you need to delete the default header so that IO uses plain text. You should add this at some point in your code:
delete Y.ModelSync.REST.HTTP_HEADERS['Content-Type'];

Categories