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.

10
  • It's upto you, if you are good with javascript then this approach is good, jquery ajax is handy otherwise! Commented Nov 26, 2015 at 5:26
  • What exactly is the problem? Commented Nov 26, 2015 at 5: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! Commented Nov 26, 2015 at 8: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. Commented Nov 26, 2015 at 19:11
  • 1
    It's definitely not about sanitize content but about requesting content using javascript, ajax and php. Thanks @cocco Commented Nov 26, 2015 at 20:38

2 Answers 2

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') {
...
Sign up to request clarification or add additional context in comments.

7 Comments

"You should not pass parameter data through HTTP header" why not?
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.
open a big website and check the headers. .. shure 'get date' is probably not appropriate. but something else would be .
btw you should add that to the answer(as the comments get deleted) it's a very valid point. the misuse of headers.-
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.
|
-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.

11 Comments

This answer is too long and confusing, it contains much personal opinion and does not really provide a helpful answer.
Can you please be more precise about what is confusing? So i reedit that part.
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.
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.
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
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.