簡體   English   中英

CURL沒有將數據發布到URL

[英]CURL not posting data to URL

我有一個簡單的表格,我想將其轉換為PHP后端系統。

現在,此表單具有提交到URL的操作-僅在提交名稱為postdata和正確信息的數據(已編碼的xml)時,URL才接受邀請。

postdata -請注意,輸入名稱稱為postdata並且該值包含經過urlencodedxml ,它可以正常工作。

<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內容未找到數據,因此將其重定向到未找到的頁面。)

302不是錯誤; 這只是意味着您需要轉到重定向的URL。 瀏覽器會自動為您執行此操作。 在PHP代碼中,您必須自己做。 查看302上的Location標頭。

我試圖看看是否有一種方法可以告訴Curl進行重定向。 許多語言的HTTP庫都支持。 該線程似乎暗示CuRL也支持它- 有沒有辦法通過命令行cURL跟隨重定向

您的代碼按預期運行,我正在獲取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> )

結果是。 問題出在接收方,它無法正確處理。

您需要在curl中遵循302重定向。 通過添加位置標記,這相對容易做到。 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); 這等效於在CLI上執行curl -L 你可以看到一個例子在這里的PHP文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM