2015-09-24 80 views
1

我试图发送一个字符串到PHP服务器,但由于某种原因,我无法读取服务器上的字符串...我尝试了很多方式来打字它,但它似乎我从来没有得到正确的语法。任何人都有线索?发送字符串到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); 
?> 

对于他们想知道,如果我硬编码$参数与右字符串,它的工作原理,所以可执行文件是没有问题的。服务器不能获取$ _POST中字符串的值。

+0

什么是命令的值就发出之前?那么$ _POST数组的值是多少? –

+2

你可能会在你的$参数中使用['escapeshellarg'](http://php.net/escapeshellarg)。如果我可以在服务器上运行任意命令,我可以做一些非常令人讨厌的事情(比SQL注入更糟糕)! –

+0

到目前为止,命令的值是text_1和text_2的连接,所以我确认我发送的字符串是好的。对于$ _POST,我不知道,因为它的服务器端我不知道如何检查它,因为我不能使用像alertbox这样的东西来弹出内容。我试图简单地在服务器上捕获它并将其扔回到JavaScript客户端,但它不起作用。它把我扔回垃圾箱。但是我得到这个错误:Undefined error index:command。 – MacGruber

回答

3

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); 

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

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

P.P.S. escapeshellarg()将使您的命令将整个$_POST['command']字符串视为一个参数。如果你不想要,那么你需要从你的JavaScript发布数组

// 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)); 
?> 
+0

耶稣基督它的作品,你得到我所有的感谢@火箭Hazmat! – MacGruber

+0

不客气:-) –

相关问题