I want to know what is the safe method to send php data to js. I found by search to start php tags in js and pass data by this way.
var jsVar = "<"+"?php echo $phpVar;"+"?"+">";
But it seems a dangerous way to pass data exposing threats. I want to know whats alternative way to do same that is safe.
I'm not entirely sure what you mean by "safe", but if I understand your question correctly, you can inject data from PHP directly into your JavaScript using json_encode:
var jsVar = <?php echo json_encode($phpVar) ?>;
If all you want to do is to inject actual PHP source code into your script, then just print it as a string:
var jsVar = "<?php echo '<?php echo $phpVar ?>' ?>";
I can't imagine this is what you mean though, as I can't think of a reason for wanting to do this :)
I want to know whats alternative way to do same that is safe.
I'm not sure what you mean by "safe", but you have to assume that any data you send to the client's browser can and will be viewed by a sufficiently-motivated user. You can secure the data from prying eyes in transit (by using SSL, e.g., https), but the client user's browser needs to be able to read the data, which means the client user can too.
You can raise the bar slightly (for instance, by obfuscating the data you embed in the page, by supplying it only in response to an Ajax call, etc.), but with today's 'net and web tools (which are increasingly just embedded in browsers) a sufficiently-motivated user will get around the precautions you take (by stepping through your code and looking at the variable you store the de-obfuscated data or the data from the Ajax response in, for instance).
If you want to raise the bar further, you can require a plug-in like Flash or Java and send obfuscated (or even encrypted) data to your flash app / Java applet and de-obfuscate / decrypt it within the app / applet. But that just raises the bar to the level of someone with debugging tools for Flash or Java.
Probably not worth the bother, I bet you have better things to do. :-)
If you don't want the user to see the data in question, don't send it to them, keep it on your server where it's safe and have the browser ask for only the information it's actually allowed to show the user.
json_encode is the best way to sent back.
echo json_encode($phpVar)
If its your data coming from your database this is pretty safe.
The problem occurs when you are storing and re-displaying data entered by the user. In which case you need to ensure that there is no possibility of executabe javascript being embedded in the data. Removing or escaping '"{}();+-/* and thier hex equvalents should do it.
You could use json_encode as suggested in answer this
Related
I have a form which i'm sending with jQuery post function to a php script.
The in the php script i do some checkings and send back a response with a formate like so:
$output = json_encode(array('type'=>'error', 'text' => 'your id is wrong!'));
die($output);
in the page where i have the form i can use a simple way to fire some functions based on the response. for example:
if(response.type == 'error'){
output = '<div class="clienConError">'+response.text+'</div>';
$(".results").hide().html(output).slideDown();
}
which means if it is the response is set as error type one do this and that...
My question is:
Is it possible to send back a jQuery function? so instead of saying: if it's a response set as error type do this. i say never mind what response is it, just do what the response tell you (for example hide some element, inject some html some where and so on... all kinds of jQuery functions).
If it is possible it will give me a few advantages. one of them is the ability to actually hide some jQuery functions (in the php script).
Although this is generally not recommended, it is possible to return JavaScript code from a PHP script, preferably with the appropriate Content-Type: text/javascript header.
At client side, you may execute the generated code using eval or injecting it in the page via a newly created <script> tag.
Dynamic scripts are discouraged for several reasons:
Harder to maintain: the generated code is –by essence– not static, and thus you can never see and edit the whole code as with a static file.
At best sloppy from the security point of view: allowing execution of arbitrary code is never a good idea, and attackers will more than certainly try to leverage this to perform client side attacks such as XSS.
Not friendly towards optimizers: contrary to a whole static script which can be parsed and optimized as soon as the file has finished loading, multiple fragmented bits of script cannot benefit from optimization.
Moreover, attempting to hide client code is a battle already lost. If the code is executed client side, then it is visible client side, period. Any user, and I insist, any user, can open the F12 debugger of their browser and place breakpoints or use step-by-step mode. More savvy users might overwrite the eval function or hook the beforescriptexecute event to inspect what’s going on. And there are even more ways.
The best you can do is obfuscate your code, with possible loss in performance and complexification of your workflow.
The only way you could really do this is by returning a javascript expression in text (wrapped in double quotes) in a JSON object. You would then need to eval() the response which isn't great for a variety of reasons - injection, performance, debugging.
I'd suggest against this approach anyway as you are overlapping the boundaries of what a client and server should be doing - tightly coupling both layers.
It is possible using eval() but it is not recommended due to performance and security reason. eval() executes the argument passed to it. So you can send the jquery function as a string and pass it to eval() to execute it on client side.
Sample Code:
var command= 'var output = \'<div class="clienConError">Here is the response</div>\';$(".results").hide().html(output).slideDown();'
eval(command);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='results'></div>
Is it possible to have a secure piece of Javascript code in a web application? By secure I mean that we can do things like query the server for permissions, and do operations that cannot be altered by the client?
Example:
var flag = 0;
$.ajax({
async: false,
url: "/check_permission_script.php",
success: function(data){
flag = parseInt(data);
}
});
if (flag != 1){
display_normal_content();
}else{
display_secure_content();
}
Here I want to make a query to the server to check if the user has permission to see the secure content. If they have the permissions, then we use display_secure_content() to show them the secure content, if not, we use display_normal_content() to display normal content. The problem is, that via a debugging terminal, it is easy to set the flag variable == 1 on the client computer, or just call the display_secure_content() function directly.
My motivation for doing things this way is to have nice web app that uses ajax to get new content, without having to reload the page. I like this instead of having to reload the page.
So the question is, can we have JS scripts that are secure against client manipulation? Or is this simply impossible by the nature of the web infrastructure?
Thanks!!
By the very nature of JavaScript, this is not possible.
Anything you want to not be seen by the client cannot be sent to the client at all. All authentication/authorization should happen server-side.
You can still use AJAX for loading data in your interface, but make sure the checks are in place server-side to keep sensitive data from leaking out.
Short answer, no - not with JavaScript alone. JavaScript executes on the client-side, so anything you put in it is accessible and by extension modifiable by the client.
Several tools exist to help with "security through obscurity" such as obfuscating the code, but this will not help you for your end goal.
What could help, given your current setup, is through Ajax you contact a server-side PHP page that handles all security/validation and returns what content to display. Doing this, the client-facing JavaScript only has the ability to "request", not to validate or choose what to display.
You could query the session id against your internal database and return a secure public/private key encrypted token which contains a key for decrypting a blob of data. Then use this as a parameter of the javascript function, which uses this returned key to decrypt the blob.
This solution does not require reloading the page, and whilst it works in theory, you would have to return the page with the secure content encrypted with a different key each time. I wouldn't recommend actually trying this.
The server should know what the user can and can not see. If the flag is changed on the client, the server should not trust it, it should do a validation when it gets the request. Security 101 stuff
JavaScript is a client side scripting language. It's meant to be this way.
If you need a secure script, use PHP.
Alright, so I've looked at a ton of questions, but I only found 1 that resembled what I am trying to do. Here is the link to it: Passing POST data from one web page to another with PHP
I want to pass data from one PHP file(we'll call it editData.php) to another PHP file(we'll call it submitData.php). Neither file has any HTML elements (pure PHP code I mean). The first file(editData.php) receives $_POST data, edits it, and needs to send it to the second file. The second file(submitData.php) needs to be able to read in the data using $_POST. No sessions nor cookies can be used I'm afraid.
In the linked question above, the answer accepted was to create hidden fields inside a form and POST the data from there. This worked for the OP because he had user interaction on his "editData.php", so when the user wanted to go to "submitData.php", he would POST the data then.
I can't use this solution(at least, I don't think I can), because I am accessing (and sending $_POST data to) editData.php from a javascript AJAX call and there will be no user interaction on this page. I need the modified data to be POSTed by code, or some other way that does the transfer 'automatically'(or 'behinid-the-scenes' or whatever you want to call it). submitData.php will be called right after editData.php.
I don't know if I can rewrite submitData.php to accept GET data, so count that out as well (it's a matter of being able to access the file). I really don't want to echo stuff back to my original JavaScript function(and then AJAX again). I am encrypting info in editData.php, and (while it sounds silly to say it) I don't want to make it easy for someone to develop a cipher for my encryption. Returning values after being encrypted(viewable with Inspect Element) would make it too easy to decipher if you ask me.
I feel like this issue could come up a lot, so I'd expect that there is something obvious I'm missing. If so, please tell me.
tl;dr? How can I send data to a PHP file via the POST method while only using code in another PHP file?
Well you might consider just streamlining your approach and including the submitData logic at the end of the editData file. But assuming that this is not possible for some reason (files live on different systems, or whatver), your best bet might be to use cURL functionality to post the data to the second script.
If the files are on the same server though I would highly recommend not posting the data to the second script as this will basically just double the amount of requests your web server needs to handle related to this script.
I have some variables set in Javascript. Further down the script I want to use these values in PHP. I realise I need to POST/GET them with jQuery, but I don't understand either function fully, even after looking at the manuals.
Could somebody break it down and explain the parameters?
Would I be better off using GET or POST in the instance?
Can the URL specified be the same as the current page e.g. index.php?
Thanks very much for your help.
You can not do this unless PHP is writing the javascript. PHP is on the server side and will be parsed before Javascript is ever seen by the client. Any variables set by JS will NOT be seen by PHP on the same request.
It's really just a question of style, really.
GET places all key/value-pairs in the URL field, whereas POST puts it in the HTTP body. Since URLs are limited in length, POST is preferred for longer, larger sets of data or data needing to benefit from TLS/SSL encryption.
So let's say we have a key: articleID. You want to pass 1 to articleID, so that the backend can contact the database and retrieve the article in question.
If you make a GET request, you'd invoke the following URL:
index.php?articleID=1
If you use POST, you'll put the data in the request body itself, so you wouldn't be able to tell what value you sent to the server without opening the packet in question and examining the request.
You'll find more information on how to perform these requests back at jQuery's reference site. More information about GET and POST.
You are the architect of the application, so you would know best what method to use. As for contacting the view itself, it's certainly possible albeit questionable from an architectural point of view.
I'd like to inspect the session variable. Best case something that works in the firebugs little interpreter, but if I have to put it in the file thats fine. Right now I just made a short PHP to output $_SESSION, but if I could find something analogous to be done right in the browser that would be ideal. document.cookie doesn't seem to do what im looking for, at least not that i see.
Basically looking for something analogous to $_SESSION that I can use in javascript
EDIT - was trying to see if i could get anything more than, or extract the meaning PHPSESSID=o147cf52u9d7qr251hc3n6ilu2; ASESSIONID=101wvpe-3FA77F204CFF55BA61E696AD3F62F0F8 on the client-side. As it stands I guess i can just write a small ajax function to a url that echos the session. Thanks for the help!
PS - Do those document.cookie values have anything to do with whats inside the session, or are they just identifiers to tell one session from another?
Session data is stored on the server. It isn't accessible to client-side JavaScript unless you manually expose it (e.g. by writing a PHP program that dumps it to JSON and delivers it over HTTP).
The browser just gets a cookie containing a token that identifiers which packet of session data the server side programs should open for a given client.
Just look at what cookies are set in your browser: Firefox,
Chrome, etc.
Edit: oooh, after re-reading your question, you want to ACCESS the session data.
That's not possible via JavaScript for very good reason. XSS would be a breeze. Besides, the data is stored on the server, which JS has no access to (thankfully).
It's not possible to do what you're asking.
I am using FirePHP to debug variables from my Ajax calls, maybe it is what you are looking for?
You can't access PHP sessions within JavaScript directly. You could however make an Ajax call to a PHP script which will return the PHP sessions. This is your best option.