2015-10-20 128 views
1

我有一個簡單的表格,我想轉換成PHP後端系統。CURL不發佈數據到URL

現在這個表單有一個提交到URL的動作 - 只有當名稱爲postdata且正確信息的數據被提交(xml已被編碼)時,該URL才接受邀請。

作品: - 請注意,輸入名字叫做postdata和值包含xml這一直urlencoded和它完美的作品。

<form name="nonjava" method="post" action="https://url.com"> 
    <input name="postdata" id="nonjavapostdata" type="hidden" value="&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;" /> 
    <button type="submit" name="submit">Button</button> 
</form> 

不過,我想通過PHP中的postdata元件移動的很多信息都是通過這種方式傳遞到實現以下。

請注意:鏈接是https,但它不是在本地工作,所以我不得不在CURL內禁用它。

<?php 
    $url = 'https://super.com'; 
    $xmlData = '<?xml version="1.0" encoding="utf-8"?> 
    <postdata 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
     <api>2</api> 
    </postdata>'; 

    $testing = urlencode($xmlData); 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, "postdata=" . $testing); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 
    curl_setopt($ch, CURLOPT_VERBOSE, true); 

    $response = curl_exec($ch); 

    // Then, after your curl_exec call: 
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); 
    $header = substr($response, 0, $header_size); 
    $body = substr($response, $header_size); 

    echo $header_size . '<br>'; 
    echo htmlspecialchars($header) . '<br>'; 
    echo htmlspecialchars($body) . '<br><br>'; 

    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    echo "$http_status for $url <br>"; 
?> 

我不斷收到302錯誤(這是URL內容沒有找到數據,以便其重定向到找不到網頁。)

+0

我想你正在尋找CURLOPT_FOLLOWLOCATION curl標誌 – Smokie

回答

0

302沒有錯誤;這僅表示您需要轉到重定向的網址。瀏覽器自動爲你做。在PHP代碼中,你必須自己做。看看302上的位置標題。

我試着看看是否有一種方法可以讓Curl通過重定向來跟蹤;很多語言的HTTP庫都支持這一點。此線程似乎表明,捲曲也支持它 - Is there a way to follow redirects with command line cURL

+0

curl_setopt($ ch,CURLOPT_FOLLOWLOCATION,true); – Smokie

0

你的代碼的工作,因爲它應該是,我得到POST數據:

Array ([postdata] => <?xml version="1.0" encoding="utf-8"?> <postdata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/20 01/XMLSchema"> <api>2</api> </postdata>)

結果。問題在於接收方,它沒有正確處理它。

+0

非常多 - 發佈數據,即xml數據需要htmlencoded併發送到URL。如上所述,代碼的HTML版本可以在沒有任何php的情況下完美工作。 –

+0

不是很確定你想達到什麼嗎?也許你想調用htmlentites:'$ testing = urlencode(htmlentities($ xmlData));'? –

0

您需要按照捲曲中的302重定向。通過添加位置標誌這相對容易。 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); 這相當於在CLI處執行curl -L。你可以在php文檔中看到一個例子here