Save php object in client side [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Is there any way to save a php object in the client side, so when I further need it I don't need to make Ajax request to get another new.

Yes -- use an HTML5 localStorage key to save whatever data you need:
localStorage["hi"] = "ho";
// and then later ...
alert(localStorage["hi"]);
Strings saved into the browser's local storage will persist when the user navigates to a new page on your site, or returns to your site later. Its browser support is pretty good -- even IE8+ supports it.
One note: you can only save string data. So, if you have an object, then you'll need to use JSON.stringify / JSON.parse:
var user = { firstName: "foo", lastName: "bar" };
localStorage["name"] = JSON.stringify(user);
// and then later ...
var restoredUser = JSON.parse(localStorage["name"]);
if (restoredUser)
alert("Hi, " + restoredUser.firstName);

You can use object serialization/deserazlization as explained here storing php objects on html form element and passing php objects through GET method?
serialize the object and encrypt the output xml string that goes on client
Then when client send request back you can decrypt the xml string and restore the object on server side by using deserialization
About encryption see this one Simplest two-way encryption using PHP
And also you can use HTML 5 client local storage as said above but this may not work in older browsers by default see localStorage supported browsers
And again it is really depends on what you exactly want to achieve and what kind of data you want to store, in some cases you can just simply use server caching so in such case you do not need to store the whole object on the client at all.

Sure, you can certainly store a PHP object at the client side. Eve an object, which contains references to object, arrays as member variables...
But don't trust anything coming back from the client that you
forwarded before to the client!
An attacked can easily change or replace the serialized object at the client side. Therefore, it's extremely dangerous to store server-side objects at the client side.
That said, here is how to store a PHP object at the client side
First, serialize the object:
$serializedObject = serialize( $someObject );
Next, save the object using local storage at the client side (base64_encode() 'hides' quotes):
<script type="text/javascript">
localStorage["soAccessor"]
= "<?php echo base64_encode( $serializedObject ); ?>";
</script>
Finally, you might pass it back to the PHP-side using e.g. a hidden field of a form.
In case you need to deserialize something back to its original object state, use deserialize(). Note, that you need to require_once() each object's class definition before doing the deserialize operation.
During deserialization, PHP tries to __wakeup() serialized objects. This won't happen correctly, if the class isn't orderly defined yet.

Related

store javascript data in PHP Variable [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 2 years ago.
I am not familiar with Javascript at all. I need to retrieve the value from externalReferralProgram . Which is in json format.
I want to get the value of this and store it in a PHP variable.
const FTXRest = require('./');
const ftx = new FTXRest({
key: 'apikey',
secret: 'apiseceret'
})
ftx.request({
method: 'GET',
path: '/api_key_status'
}).then(console.log);
PHP is a server-side language. Javascript is a client side language.
What happens is PHP will run whatever stuff its supposed to, then send whatever HTML and javascript you tell it to send to the browser. At this point, PHP will wipe out this session and start handling other requests. The browser then receives this content and starts running the javascript.
With this understanding, you can see that it really doesn't make sense to store a javascript value in a PHP variable - by the time the javascript is running, PHP has already long-forgotten about this request.
Your best bet is to either find a way to do the same javascript logic in PHP, or, make the javascript send a REST request back to the PHP server with whatever data you need, so that PHP can do further processing on it (this means creating a separate PHP file that'll receive javascript data from $_GET or $_POST).
Use json_decode
Takes a JSON encoded string and converts it into a PHP variable.

Safely pass object to client in Node.js/express

A common question is how to pass an object from Node.js/Express.js to the browser. It's possible to do that using JSON stringify, but if the object contains user-provided data, that can open the door to script-injection and possibly other attacks.
Is there a downside to the approach mentioned in this link using Base64?
https://stackoverflow.com/a/37920555/645715
Related links:
Passing an object to client in node/express + ejs?
How to pass a javascript object that contains strings with quotes from node.js to the browser?
Pass a NodeJS express object to AngularJS 1.6
Passing an object to client in node/express + ejs?
Using Base64 encoding does solve the immediate problem of passing back an injection attack, but it doesn't necessarily solve the issue of having a possible injection attack floating around out there. For example, this fiddle shows that it does prevent the immediate issue : https://jsfiddle.net/9prhkx74/
var test2 = JSON.parse(window.atob('PC9zY3JpcHQ+PHNjcmlwdD5hbGVydCgndGVzdDInKTwvc2NyaXB0PjxzY3JpcHQ+'));
This won't show an alert box, it'll just throw an error about invalid JSON. But if you change it to the literal string, it'll show the alert box (injection vulnerable)
var test2 = JSON.parse("</script><script>alert('test2')</script><script>")
Now if you are immediately parsing it to a JSON object, it'll blow up, and everything will be "safe". But if you assign it to a value because you are going to pass it around some more etc, you still have a potential issue out there.
Instead of putting a bandaid on the injection itself, I'd suggest fixing it in the first place and properly escaping data before passing it back to the client or processing it on the server side.
There are plenty of libraries that can help do this
https://www.npmjs.com/package/sanitize
https://www.npmjs.com/package/express-sanitizer
Here's a pretty good article that kind of highlights why it is important to sanitize and not just just patch over potentially malicious data : https://lockmedown.com/5-steps-handling-untrusted-node-js-data/

Ways to store dynamic data produced by jquery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am learning web development. I have come across a part in jquery where i can dynamically produce html elements like div table etc. But i wanted to know how to store these dynamically produced data. What are all the ways to store these jquery dynamic data?? And if i want to store it in mysql how to do?? It will be helpful if you have any reference links or code. Pls help me with this
The dynamic data often comes from a JSON string. JSON represents an object (or a set of objects) that can be used directly in Javascript.
Using Jquery, you can get JSON with this utility method : getJSON( url [, data ] [, success ] )
So you have to provide an URL responding with JSON, to be used as the url parameter in getJSON function.
It can be either a static file (ie http://domain:port/data/myData.json) or a dynamic content generated by a server side process in the language of your choice (PHP, Java, JS with NodeJS...), ie http://domain:port/myData.php?filter1=value1.
Note : JSON is the most standard format for transferring objects to Javascript, but it could any format (CSV, XML, ...)
In the callback method of getJSON, you will be provided a plain Javascript object that will contains everything that was in your JSON file, and you could use it to produce whatever you want (html elements like div table etc).
If you need to request a SQL backend, you will have to use a server side process to do the SQL request and map it back to a JSON object.

How to use JSON.stringify() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to consume data from an API using REST call .
I've succeeded to get data from the API :
You can check demo on jsfiddle : http://jsfiddle.net/zTXyq/33/
Now , I am trying to perform the work to get different resources from this API
I am reading these two articles :
- http://www.jquery4u.com/demos/ajax/
- http://welcome.totheinter.net/tutorials/model-view-controller-in-jquery/
I would like to know why do we use JSON.stringify() if we can show data in HTML pages .
Why do we use so-called 'class'/'model' to parse data using json ?
Regards ,
JSON is a data structure, which means it serves to transport variables, arrays and stuff.
Sending variables in html code would be silly - that is why we use JSON.
JSON.stringify() is an utility function, which is most commonly used for debugging, when you want to print some variable to console, but there are some other uses, too.
console.log( JSON.stringify(myObject) );
What the function does, is that it takes an object, array or about anything else, and makes a readable string of it, while simply using something like this ↓↓ would give you only [Object].
console.log( myObject );
If all you really want is to send some HTML to be displayed, then you don't need to bother with JSON at all, and just use jQuery.load() or something similar.
I hope you will agreee that in javascript code JSON objects are nice and easy to use, for example
var jsonObj { "p1": "1", "p2": "2"};
if ( jsonObj.p1 == '1' ) { // do something }
But if we want to pass that object around to non javascript code, for example to a PHP script, we cannot do it.
So the stringify comes into play, we stringify our JSON object i.e. convert the whole object to a string, now we can pass this around to anything that has the ability to convert it back to something useful. So PHP has the json_decode() function to convert a stringified json object/array to a PHP object/array so it becomes useful again.
Now when we want to pass data back from PHP to javascript we convert a PHP object/array to a json string using json_encode() and we can now pass an object/array back to a javascript as a string for it to use JSON.parse() on so it can convert it back to a usable object/array.
So in summary, stringify allows us to convert language specific formats for objects/arrays into a universally available format i.e. a string. Therefore any language that provides a method of converting this stringified format into its own language specific formats for objects/arrays can use this data and of course return it again via the stringified format.

How to show a friendly error message using Open-flash-charts2?

If my JSON data-file comes from a database result set and that result set is empty, how do I tell OFC2 to display an error message, instead of crashing because of a malformed JSON string?
Add tags for javascript and actionscript-3 to this question and you should get a load more views and useful responses than you currently are, with more precise details than I am giving. Post the actual JSON string that is causing you the problem and that you would like to be guarded against. That way people can suggest a regexp to catch it, treating it as a string rather than as JSON data at some point before JSON.decode() happens.
In more detail:
You can catch it in two places. One route is to switch over to using the javascript interface to OFC2 and use client side javascript to detect the bad string. This allows you to modify the JSON string client side. See http://teethgrinder.co.uk/open-flash-chart-2/tutorial-5.php for that approach. One downside is that the clients must have javascript enabled for this to work.
Alternatively, since OFC2 is LGPL, you or an actionscript developer can dive into the OFC2 source code and do the same thing there. I am not an actionscript developer so you are better off ensuring you get a reply from one.
The main thing is to add those two tags to this question. 22 Views is way too low for a question with a bounty of 500. Hope this helps.
Several solution avenues are possible, depending on your level of access to the server and your knowledge of JavaScript and/or any server-side platforms.
With access to database
Depending on the kind of data you are displaying, it might be possible to add dummy records for those queries that would otherwise have returned an empty set. If you have access to the query definition, you may check for the empty set in the DB-query. For example, if you're on MS SQL Server you could check the condition with some T-SQL statements.
With access to server
If you have access to the server side script generating the dataset, add a condition that returns some default value that OFC2 will handle correctly.
With access to another server or serverlocation
If you don't have access to the specific script, you may consider creating a new script at another location that queries the original script and replaces empty results with the default value.
Client-side only
You can add the JavaScript open_flash_chart_data function (see tutorial) to replace empty datasets. OFC2 can use that function as data source.
Hope this helps.

Categories