如何更好地保护来自恶意用户的php,jquery,ajax请求
我通过jquery的getJSON方法发送大量数据,一个函数的例子是
I send a lot of data through jquerys getJSON method, an example of a function is
function doSomething(sid){
if(sid){
$.getJSON("ajax/ajaxDoSomething.php",{sid:""+sid+""}, function(data){
//alert(data);
if(data.success == true){
$('#add_vote_div').html('vote received');
$('#list_data_div').html(data.html);
}
else{
$('#add_vote_div').html(data.message);
}
});
}
}`
问题在于,任何人都可以查看源代码,并查看将GET数据发送到的php文件的位置,因此,您只需将浏览器指向那里并将数据附加到URL.我会检查数据以确保其数据类型正确,但是我根本不希望用户能够访问该URL.
The problem is that anyone can look at the source and see that the location of the php file its sending the GET data to, therefore you could just point your browser there and append data to the URL. I do checks on the data to make sure its the right data type, but i dont want users to be able to go to the url at all.
我想也许所有的ajax文件都可以放在主文档根目录下,这可以工作,但是jquery无法链接到绝对路径,例如
I thought maybe put all the ajax files behind the main document root which would work but jquery can't link to absolute paths like
$.getJSON("var/www/ajax/doSomething.php",{sid:""+sid+""}
(主文档根目录为var/www/html/)
(main document root is var/www/html/)
如果他们制作了一个效果更好的$ .postJSON,但它不存在,有什么主意吗?
if they made a $.postJSON that would work better, but it doesn't exist, any ideas?
它只会稍微提高黑客攻击的门槛,但是您可以通过 jQuery.post
(就是这样). jQuery.getJSON
只是ajax
的包装(.post
和.get
也是如此).从 getJSON
文档:
It only raises the bar to hacking very slightly, but you can POST JSON via jQuery.ajax
(that's a link) or jQuery.post
(so's that). jQuery.getJSON
is just a wrapper for ajax
(as are .post
, and .get
). From the getJSON
docs:
这是Ajax的简写功能,等效于:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
因此,要实现您的postJSON
概念,只需向其中添加一个type
参数:
Thus, to do your postJSON
concept, you'd just add a type
parameter to it:
$.ajax({
url: url,
type: 'POST', // <== the new bit
dataType: 'json',
data: data,
success: callback
});
如果确实愿意,可以将postJSON
添加到jQuery
对象,对参数进行预处理,然后调用$.ajax
.这基本上是从 jQuery来源复制并粘贴的,但将.get
切换为.post
:
If you really wanted to, you could add a postJSON
to the jQuery
object, pre-processing the arguments and then calling $.ajax
. This is basically a copy-and-paste from the jQuery source, but switching .get
to .post
:
if (!jQuery.postJSON) {
jQuery.postJSON = function( url, data, callback ) {
return jQuery.post(url, data, callback, "json");
};
}
请记住,伪造POST仍然很容易.不像GET那样简单,但仍然很容易.
Mind you, it's still pretty easy to fake a POST. Not as easy as a GET, but still pretty easy.