簡體   English   中英

PHP curl只發送一次POST數據

[英]PHP curl only sending POST data once

我有以下PHP代碼:

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "https://10.0.0.99/api/login");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST,           1);
curl_setopt($ch, CURLOPT_POSTFIELDS,     "somethingsomething");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: text/plain',
    'Content-Length: 18')
);

$cookie = curl_exec($ch);

curl_setopt($ch, CURLOPT_URL,            "https://10.0.0.99/api/getcmds");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIE, "cookie=".$cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST,           1);
curl_setopt($ch, CURLOPT_POSTFIELDS,     "");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: text/plain',
    'Content-Length: 0')
);

$response = curl_exec($ch);
$json = json_decode($response, true);

curl_setopt($ch, CURLOPT_URL,            "https://10.0.0.99/api/cmd/" . $json["value"]);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIE, "cookie=".$cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST,           1);
curl_setopt($ch, CURLOPT_POSTFIELDS,     "on");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: text/plain',
    'Content-Length: 2')
);

curl_exec($ch);

curl_close($ch);

對curl_exec的第一次調用按預期方式發布了字符串,並返回了響應。 第二通電話也按預期工作。

但是,第三個調用不會將字符串“on”發布到服務器上。 它可以正確獲取返回的數據(如果不帶“ on”,則表示錯誤),但是服務器從不接收發布的數據。

代碼本身在命令行中使用-f標志在PHP 5.5.30上運行。 Curl Verbose模式顯示正確設置了Content-Length,但是未顯示任何有關已發布數據的信息。 該帖子的其余部分似乎是正確的,只是沒有數據到達。

(PS:這不應該是生產代碼,而只是我在玩的東西,所以請不要評論代碼質量/安全性。)

您可以嘗試關閉連接,然后重新開始進行新的呼叫/請求。 我親自做這件事。

來自cURL上的php.net文檔: PHP:curl_setop

至於CURL_POSTFIELDS :這個參數可以作為urlencoded字符串傳遞,如'para1 = val1&para2 = val2&...',或者作為一個數組,字段名稱為鍵,字段數據為值。

在您的情況下,您設置一個空變量$_POST['on'] 如果您希望它具有某些特殊的價值:

curl_setopt($ch, CURLOPT_POST,           1);
curl_setopt($ch, CURLOPT_POSTFIELDS,     "on=value");

暫無
暫無

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

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