如何使用Ajax使用URL或其他方法注入特定的PHP函数?

时间:2010-01-22 15:46:36

标签: php ajax code-injection

我正在从JS的领域转向php和Ajax。我过去曾经涉猎PHP。 我非常感谢stackoverflow在帮助我解决基本问题方面提供了多少帮助。

我说我有一个名为#divName的div。

我使用以下JS for Ajax。其中一些只是伪代码。

var request = false;
   try {
     request = new XMLHttpRequest();
   } catch (trymicrosoft) {
     try {
       request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (othermicrosoft) {
       try {
         request = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (failed) {
         request = false;
       }  
     }
   }

   if (!request)
     alert("Error initializing XMLHttpRequest!");

   function getAjaxInfo(<name of the php function???>) { //<<<<< this is the function I need help with
    var myFunction= nameOfPHPfunctionIJustGot;
     var url = "filename.php?func=" + myFunction;
     request.open("GET", url, true);
     request.onreadystatechange = updatePage;
     request.send(null);
   }

  function updatePage() {
     if (request.readyState == 4) {
       if (request.status == 200) {
         var response = request.responseText;
             document.getElementById("divName").innerHTML = response; //probably going to use Jquery append here, but this example works.
               } else
         alert("status is " + request.status);
     }
   }

我有我的fileName.php文件:

<?php

function header() { ?>
   header content goes here
<?php }

function footer() { ?>
    footer content goes here
<?php }

?>

我的目标是当我执行getAjaxInfo()时,我可以提取我想要的任何PHP函数。

所以,如果我做一个onClick="getAjaxInfo(header),它将获得php头函数,将其应用于javascript函数,然后将其应用于div。

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:2)

尝试:

$func=$_GET['func'];
if(function_exists($func)) $func();

通过这种方式,您可以获得GET传递的函数名称并执行它。

如果您希望只能呼叫某些功能:

$allowedFunctions=array("header","footer");
$func=$_GET['func'];
if(in_array($func,$allowedFunctions) && function_exists($func)) $func();

答案 1 :(得分:2)

了解@ VolkerK的建议,并添加失败功能:

$func = $_GET['func'];
$allowed = array('header', 'footer');
if (in_array($func, $allowed) && function_exists($func)) $func();
else default_action();

答案 2 :(得分:2)

<?php

$allowedFunctions = array(
   'header',
   'footer'
);

$functionName = $_GET[ 'func' ];

if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
    $functionName();
}

/* your function definitions */
?>

$allowedFunctions是用户定义(i.o.w. your)php函数的白名单数组,您希望ajax调用允许执行。如果您不保留此白名单,则您的脚本将具有潜在危险,因为它允许任何人执行任意功能。这是你绝对不想要的东西。