php curl post两次

时间:2017-04-20 11:47:15

标签: php curl

我知道这是重复的问题。我尝试了stackoverflow.com的所有解决方案,但我无法解决它。 这是非常随机的行为。当php curl post到目标服务器api时,有时相同的请求会被发送两次到目标。我检查了源php是否已刷新,但php未刷新。我注意到的另一件奇怪的事情是,我只获得curl output重新发帖请求。我没有收到第一份原始请求的curl output

$curl_unit = curl_init($URL);

curl_setopt($curl_unit, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl_unit, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_unit, CURLOPT_POST, 1);
curl_setopt($curl_unit, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($curl_unit, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_unit, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_unit, CURLOPT_INTERFACE, gethostbyname($_SERVER['HTTP_HOST']));
curl_setopt($curl_unit, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
curl_setopt($curl_unit, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$curl_output = curl_exec($curl_unit);
$code = curl_getinfo($curl_unit, CURLINFO_HTTP_CODE);

curl_close($curl_unit);
SaveMyLog("DATA RECEIVED FROM destination: \r\n" . $curl_output . "\r\n Http code response: " . $code . "\r\n");

上述代码是项目所有curl页面中php的通用代码。 后来当我在stackoverflow上找到一些解决方案时,我尝试了不同的curl代码。以下是新的卷曲代码,有时也不起作用,并发生相同的随机奇怪行为。

$curl_unit = curl_init($URL);

curl_setopt($curl_unit, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl_unit, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_unit, CURLOPT_POST, 1);
curl_setopt($curl_unit, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($curl_unit, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($curl_unit, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_unit, CURLOPT_INTERFACE, gethostbyname($_SERVER['HTTP_HOST']));
curl_setopt($curl_unit, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
curl_setopt($curl_unit, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

ob_start(); 
curl_exec($curl_unit);
$code = curl_getinfo($curl_unit, CURLINFO_HTTP_CODE);
curl_close($curl_unit);
$curl_output = ob_get_contents(); 
ob_end_clean();         

SaveMyLog("DATA RECEIVED FROM destination: \r\n" . $curl_output . "\r\n Http code response: " . $code . "\r\n");
ob_end_flush();

请注意$URL已定义$postdataSaveMyLog函数用于记录目的。

function SaveMyLog($lin, $deprecated = 'mylog.log')
{
    $logid = '';
    $date = getdate();
    $fileName = basename($_SERVER['SCRIPT_FILENAME']);
    $file = str_replace('.php', '', $fileName);

    $logfile = $file . "_" . $date['year'] . "-" . $date['mon'] . "-" . $date['mday'] . ".log";

    $fd = fopen('./logs/application_logs/' . $logfile, 'a+');
    fwrite($fd, date('Y-m-d H:i:s') . $logid . "\t" . $lin . "\n");
    fclose($fd);
    @chmod('../logs/application_logs/' . $logfile, 0666);
}

3 个答案:

答案 0 :(得分:0)

您可以尝试使用CSRF令牌,这会在每次请求后更改。

答案 1 :(得分:0)

从您的代码中我看不出它应该以如此奇怪的方式表现的原因。

所以可能还有其他一些问题。如果您从浏览器调用脚本,请确保浏览器只调用一次。

Why does a browser send two requests for the same page when it's refreshed?

答案 2 :(得分:0)

我们遇到了同样的问题,我们通过禁用或卸载 Firebug Lite 扩展解决了这个问题。