2015-09-24 145 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

不客氣:-) –

相關問題