发送字符串到php服务器并使用它


Send string to php server and use it

我试图发送一个字符串到php服务器,但由于某种原因,我无法读取服务器上的字符串…我尝试了很多方法来输入它,但似乎我从来没有得到正确的语法。有人有线索吗?

var command="";
if(document.getElementById("Text_1").value != "" && document.getElementById("Text_2").value != "")
        {
            command += " " + document.getElementById("Text_1").value + " " + document.getElementById("Text_2").value;
        }       
        alert(command);
        xmlhttp.open("POST", "server.php", false);
        xmlhttp.setRequestHeader('info', command)
                     //TRIED xmlhttp.setRequestHeader("info, command")
                     //TRIED xmlhttp.setRequestHeader('info', 'command')
                     //TRIED many others sketchy things...
        xmlhttp.send();
        //TRIED xmlhttp.send(command);
        var output = xmlhttp.responseText;

在php服务器上:

<?php
$parameter = $_POST['command']; 
$output = exec("someexecutable.exe $parameter");
echo json_encode($parameter);
?>

对于他们来说,如果我用正确的字符串硬编码$parameter,它就能工作,所以可执行文件不是问题。服务器无法获取$_POST中字符串的值

setRequestHeader用于设置请求的标头。如Content-typeContent-length

需要将数据传递给send()。对于$_POST的工作,他们需要在key=val&vey2=val2格式。实际上,在较新的浏览器中,您可以使用FormData

xmlhttp.open("POST", "server.php", false);
// To emulate a `<form>` POST
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// To get the response, you need to set a callback
xmlhttp.onreadystatechange = function(){
    // readyState 4 = complete
    // status = 200 OK
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var output = xmlhttp.responseText;
    }
};
// Create the Form Data
var params = new FormData;
params.append('command', command);
xmlhttp.send(params);

注:在运行命令之前,应该先运行escapeshellarg()。如果人们可以在您的服务器上运行任意命令,这可能比SQL注入更糟糕。

<?php
$parameter = escapeshellarg($_POST['command']);
$output = exec("someexecutable.exe $parameter");
?>

P.P.S.escapeshellarg()将使命令将整个 $_POST['command']字符串视为一个参数。如果你不想这样,你需要从JavaScript中POST一个数组

// Create the Form Data
var params = new FormData;
params.append('command[]', document.getElementById("Text_1").value);
params.append('command[]', document.getElementById("Text_2").value);
xmlhttp.send(params);

现在$_POST['command']将是一个数组,所以你必须像这样运行命令:

<?php
$parameters = array_map('escapeshellarg', $_POST['command']);
$output = exec("someexecutable.exe ".implode(' ', $parameters));
?>