Reputation: 2549
Well I'm new to PHP but thinking about these stuff has really confused me these days.
Here is my question in detail:
First the situtation is that I need to transfer the data between clients and the server. Ajax should be used to present the data at clients' side. At the server side, PHP and MySQL will be used to parse the request, grab the data and then send it back.
Then the problem comes. User data sent from the brower can contain &, %, ', " which may damage the formatted POST request or making database attack. Although we can use JS to detect them, the user is still able to send data bypassing the validation, let alone we cannot simply remove them as they may be useful to the user.
So then I checked my weapon library.
At server side, it turns out that I have too many functions to deal with them:
Apart from regular expessions I have
htmlspecialchars, htmlspecialchars_decode, addslashes, stripslashes
urlencode, urldecode, mysql_escape_string, mysql_real_escape_string
At client side with javascript, I don't have that many but still have:
escape, unescape
OK. Learning that I have so many weapons is good but...how to choose, combine and use them is really a headache for me.
For example suppose I want to have a product name called:
'%Hooray%'+&ABC
Well maybe no product will be named like this in real life but let's use it as an example.
The & mark will break the POST message.
The + may impact ajax parsing.
Single quotes may allow SQL injection.
The % mark may cause problems but I'm not sure if it will.
But I still want that name exactly the same after sending it to the database and fetching it back,
which means, the name in database can be different but its presentation in the brower should be the same.
Well this question may be a little bit too long but hope somebody could share some good experience: how to deal with user input string using those functions?
Upvotes: 0
Views: 670
Reputation:
Before sending your data via ajax, encode them: Assuming the data is a javascript array. Why an array? Because if you have a query already (ex. 'name=me&foo=b&ar') how you can solve that 'b&ar' that is clearly a value to YOU but 'b' and 'ar' for the javascript engine?
for(i in arr)
{ arr[i] = encodeURIComponent(arr[i]); }
This function replaces all harmful url characters (, / ? : @ & = + $ #) and some more.
Then you can send your query by building up like arr.join('');
But i'd use jquery and send the array right after.
On PHP side the basic rule you must obey is that you NEVER save your data without mysql_real_escape_string();
Upvotes: 2
Reputation: 13571
Serverside what you want are prepared statements, aka parameterized queries, in order to keep your DB safe (avoid SQL injection).
Client side, I would recommend JSON with defined objects and DOM manipulation, not innerText or innerHTML. The browser will escape everything it needs to in order to do a post.
Upvotes: 2