PHP:帮助保护/过滤器的AJAX调用过滤器、PHP、AJAX

2023-09-10 16:36:12 作者:你给的我全部都接受

我试图找到一种方法,以安全的罚款图层添加到我的应用程序过滤Ajax调用。请问code·贝娄任何意义?

I am trying to find a way to filter ajax calls in order to add a fine layer of security to my applications. Does the code bellow make any sense?

function is_ajax(){//Help Secure Ajax Calls
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest') return;
    else die;//no ajax
}

我的梦想是只让我的服务器(HTM或者PHP)通过AJAX访问另一个php文件中的文件。

My dream is only let a file inside my server (htm or php) to access another php file via ajax.

我不知道code波纹管不会做的更好:

I wonder if the code bellow would not do better:

if(strpos($_SERVER['REQUEST_URI'],'http://')) die;//Help Secure From URL Include Attacks

感谢。

推荐答案

由于AJAX调用总是从浏览器发出的请求不是从自己的服务器来,但客户机。即使您设置自定义标题,这些都可以很容易地被操纵在客户端。

Since the AJAX call is always made from the browser, the request is not coming from your own server, but the client machine. Even if you set custom headers, these can easily be manipulated on the client side.

如果你的目标是只允许自己的脚本来访问包含内容的AJAX脚本,我建议你生成一个标记字符串,仅适用于特定请求的URL,并在指定的时间。

If your goal is to only allow your own scripts to access the script containing the ajax content, I'd recommend generating a token string that is only valid for a certain requested url and a specified time.

$secret ="ABC1232";

$item = array(
  "time"=>time(),
  "token_id"=>"<page_url>"
);

$signed = base64_encode(hash_hmac("sha256",json_encode($item),$secret));
$item = base64_encode(json_encode($item));

$ajax_url = "myscript.php?signed=$signed&item=$item";

Ajax资源,检查记号是否有效

$item = json_decode(base64_decode($_REQUEST["item"]));

$timeout = 3600;

if($item->time < (time()-$timeout)){
  die("Invalid token - timeout");
}

if($item->token_id !== "<page_url>"){
  die("Invalid token - page url");
}

$secret ="ABC1232";
$valid = ($_REQUEST["signed"] === base64_encode(hash_hmac("sha256",json_encode($item),$secret));

if(!$valid){
  die("Invalid token");
}