0

I have the following XMLHttpRequest:

# ....
var request = new XMLHttpRequest();
request.open('GET', 'controllers/get_date.php', true);
request.setRequestHeader('Cache-Control', 'no-cache');
request.setRequestHeader('fn', 'get_date');
request.setRequestHeader('day', '27/11'  );
# ....

And get_date.php looks like this:

if($_SERVER['HTTP_FN'] == 'get_date'):
   $day = Common::sanitize($_SERVER['HTTP_DAY']);
   $data = new MyFunction($day);
   echo $data->my_data();
endif;

Basically I'm trying to get some data from $data->my_data() and all of this is working fine. However as my back-end skills are quite limited. I am wondering if this is a proper way (considering mainly security) or if I should take another approach.

Miguel Garrido
  • 1,121
  • 11
  • 23
  • It's upto you, if you are good with javascript then this approach is good, jquery ajax is handy otherwise! – Disha V. Nov 26 '15 at 05:26
  • What exactly is the problem? – Lysol Nov 26 '15 at 05:28
  • 1
    There's not a real problem indeed as far as I can see. My question is about finding a proper way considering security, performance, language usage, etc as I'm far for being a experienced developer. I've been reading a lot about how to develop server side applications with nodejs, ruby on rails, php frameworks, etc. In regards to the requirements I have this seems to do the work I need to get done. Thanks! – Miguel Garrido Nov 26 '15 at 08:36
  • 1
    From the code and information you provided, we cannot tell wether your implementation is good or not. It mainly depends on 2 factors: What's the code behind `Common::sanitize()` and: How many of those requests do you have per session. You should put more code and place it on CodeReview Stackexchange platform. – Daniel W. Nov 26 '15 at 19:11
  • Hey @DanFromGermany, I understand I've just pasted that piece of code as I am not requesting help about `Common::sanitize()` (for example) as there's heaps of content out there. Requests per session could be a good thing that I haven't thought before. Thank you. – Miguel Garrido Nov 26 '15 at 20:28
  • @Miguel Garrido my answer is mostly based of your comment. If your question is php / Common::sanitize specific, then Dan&Dan are right and my answer is totally wrong here.So pls if you tell me, i can remove it eventually. – cocco Nov 26 '15 at 20:36
  • 1
    It's definitely not about `sanitize` content but about requesting content using javascript, ajax and php. Thanks @cocco – Miguel Garrido Nov 26 '15 at 20:38
  • ok then i leave my answer here. ;) nice day! – cocco Nov 26 '15 at 20:39
  • i added some more stuff about json & php if you prefer that. – cocco Nov 26 '15 at 21:37
  • @MiguelGarrido there is nothing wrong by fetching content using Ajax. But if your `sanitize()` method is not good, you can have a security problem. – Daniel W. Nov 27 '15 at 08:37

2 Answers2

2

You should avoid passing parameter data through HTTP header. HTTP header is for the HTTP layer to proper transport its data. It has its own purpose, but not for application parameters. Proxy, firewalls, gateways, load balancers etc could all inspect and re-write the header for the purpose of the HTTP transport. Your custom 'parameters' might get re-written, removed, or run into the same namspace of other header.

Instead, I recommend you to pass using query string using GET or POST data.

For example:

request.open('GET', 'controllers/get_date.php?fn=get_date&day=27%2F11', true);

And in PHP, getting the parameters using:

$fn = $_REQUEST['fn'];
$day = $_REQUEST['day'];
if($fn == 'get_date') {
...
Quickpick
  • 163
  • 6
  • 1
    "You should not pass parameter data through HTTP header" why not? – cocco Nov 26 '15 at 18:33
  • 1
    You can say purists. But HTTP header is for the HTTP layer to proper transport its data. It has its own purpose, but not for application parameters. Proxy, firewalls, gateways, load balancers etc could all inspect and re-write the header for the purpose of the HTTP transport. Your custom 'parameters' might get re-written, removed, or run into the same namspace of other header. Application layer has all sort of ways to transfer its parameters. Why step over and take risks. – Quickpick Nov 26 '15 at 21:48
  • open a big website and check the headers. .. shure 'get date' is probably not appropriate. but something else would be . – cocco Nov 26 '15 at 21:55
  • btw you should add that to the answer(as the comments get deleted) it's a very valid point. the misuse of headers.- – cocco Nov 26 '15 at 21:57
  • 1
    I just say what it should be what it shouldn't. Of course, passing your data through http header works to some extends. But for newbies, that's not something I would encourage. There are a lot of custom http header out there but main purpose is for the proxy/gateway/load balancer to communicate. Newbies should stay away or risk hours of debug time. – Quickpick Nov 26 '15 at 22:05
  • Yup. I'll put my comments into the answer. Good talks! cocco. – Quickpick Nov 26 '15 at 22:06
  • @Quickpick note about Proxy is most important! – Daniel W. Nov 27 '15 at 08:38
-2

Yes it's up to you!

First of all compliments for using the native XMLHttpRequest, which is supported by all browsers including the mobile ones. Using the jQuery's ajax is just performance loss.

Security

When talking about javascript there is no security. Zero.

I answered a question about How can I obfuscate(protect) JavaScript? some time ago... and there is really nothing you can hide as soon as you put it online. The only thing you can do is to annoying the "hacker". Also just using the native XMLHttpRequest increases the chance that all those jQuery fans don't understandd what you do! ;)

In the above post i used headers to validate the referrer...

Performance

XMLHttpRequest It's native... so it is the fastest approach..

All other libs include many userfriendly checks that simplify everything. Many checks means performance loss.

As you may want to use ajax for more than just one action i suggest you look at the function i wrote some time ago.

How do I return the response from an asynchronous call?

function ajax(a,b,e,d,c){ // Url,callback,method,formdata or {key:val},placeholder
 c=new XMLHttpRequest;
 c.open(e||'get',a);
 c.onload=b;
 c.send(d||null)
}

I use it for various REST API's. Mostly you don't need to set the header and other stuff. You could modify it and add the support for adding header information.

I see a very bad thing in your code.

request.open('GET', 'controllers/get_date.php', true);

True???

Don't do that. that should be never used. Not even with static files. Ajax is meant to be async! You will crash the users browser if the response of the php file is not fast enough. By crash i mean the browser is stuck nothing moves until the ajax content is loaded. So if it takes 5seconds to load the file, for 5 seconds you can't do nothing. the mouse/touch events don't work also every animated elements will be frozen.gifs/videos/cssstyles.

How to send the params

Slightly more security... short params, best performance ?? yep, use the headers the headers are send before anything else. But in reality i think not much changes as the final binary data is probably the same size as if you would send it over GET & POST.

GET or POST?

If at the end the gained security of sending the headers is not enough so you want to do it the "normal" way, then there is only one important thing to consider: how much data you need to send. I prefer post.. it allows to send more data. I use FormData to do so.

var fd=new FormData(form);// this is the whole form including upload files.
ajax(url,callback,'post',fd);

Something that does not seem very obvious is JSON.

I see nowhere JSON mentioned. Ajax withoutJSON is useless. js & php without json is useless. you can't just send strings... so

php

//php array to jsonstring
json_encode($array);

//jsonstring to php array
json_decode($string);

js

//jsonstring to js array
JSON.parse(string);

//js array to jsonstring
JSON.stringify(array);

In both cases (if the server nginx,apache,lighthttp is setup correctly) you don't need to worry about encoding. JSON is automatically encoded in utf8.

PHP

Some ppl would probably suggest to comrpress the php(ajax can handle zipped files) or even add the correct mimetype.

//header('Content-Type: application/json'); // not needed
echo json_encode($data);

but in both cases it takes more time. so don't.

keep the php file as simple as possible. as it's the one that take more time. don't send elements , style or other html relative stuff. you should do that clients side. to keep the server agile.

mysql to json

https://stackoverflow.com/a/20948686/2450730


Now, looking at the comments, you use NODEJS :).

Use webSockets. use it for everything. Forget about ajax, and do everything with websockets!!!!! Bidirectional communication. And you send only the data needed. No requests, no headers... no slow stuff.

Support

Both ajax and websockets , but also server sent events are not supported by older browsers.

If that is a problem don't use those technologies. Also using jQuery to allow ajax on ie6 is just a joke....

Btw now ff, ie, opera, android, safari, ios even a 4-5 year old version of those browsers support ajax,websockets & SSE

webSockets

I really like php, mysql nginx apache... but nodejs, websockets & json ..

Thats fun pure.

simple js example.

var ws=new WebSocket('ws://YOURIP:YOURPORT');
ws.onopen=function(){ //those events are also aviable with sse
 ws.send('WS open!');//sending data to the server
 // server handles each user individually very easely.
};
ws.onclose=function(){
 console.log('WS closed!');
};*/
ws.onmessage=function(e){
 //USE JSON
 var Everythingyouneed=JSON.parse(e.data);
};

@ nodejs side....

https://github.com/websockets/ws

look at the broadcast or send the data to eah user individually.

Community
  • 1
  • 1
cocco
  • 16,442
  • 7
  • 62
  • 77
  • This answer is too long and confusing, it contains much personal opinion and does not really provide a helpful answer. – Daniel W. Nov 26 '15 at 19:07
  • Can you please be more precise about what is confusing? So i reedit that part. – cocco Nov 26 '15 at 19:16
  • I don't feel this is a good answer because the OP asked about PHP and you replied with NodeJS. The concepts might be transitive, butyou go off on a tangent about websockets when OP doesn't even *glint* about using real time communication, and some information is downright false. You won't "crash the user's browser" by sending a synchronous file. You'll certainly block your server but that won't crash the browser, that'll just destroy your server's efficiency. – Dan Nov 26 '15 at 19:35
  • No, that's wrong. All of the client actions will work fine - at worst, the client will just get a connection timeout (HTTP 500) or a upstream error (HTTP 503) if behind a forward proxy. That's not going to 'crash the browser', and by that extent you could argue that any uncaught exception will 'crash the user's browser'. The main issue with this approach is while sending a synchronous file, the server cannot serve anyone else on that same thread and blocks while waiting for I/O to transfer. – Dan Nov 26 '15 at 19:39
  • The point is if the file takes to 3 seconds to load, the browser is stuck for 3 seconds. no events(mouse,touch) or even animations(css) aviable. Its the worst thing to do.Ajax syncronous – cocco Nov 26 '15 at 19:39
  • @cocco I misunderstood, I thought the call I was reading was on the server-side. Didn't realise it was an Ajax call fo rsome reason – Dan Nov 26 '15 at 19:44
  • no problem. i'm always happy to explain what i write. – cocco Nov 26 '15 at 19:45
  • Also if you read the comments, he talks about nodejs. – cocco Nov 26 '15 at 19:52
  • PHP is for shure, always, a robust solution but these days with new technologies like websockets other server applications are needed. PHP isn't made for that...I use php alot, since 1998, there was no other same powerfull web language. Also these days PHP is essential. I have nothing to say against php ;) – cocco Nov 26 '15 at 19:57
  • It looks like you php guys take it too personal. but i also like php! – cocco Nov 26 '15 at 20:04
  • "OP doesn't even glint about using real time communication" lol , i missed that ... noone talks about realtime communication ... but yeah, your right, thats another point for websockets. – cocco Nov 26 '15 at 20:17