运行file_get_contents时,cURL执行了两次?

时间:2017-02-03 09:05:08

标签: php curl http-headers file-get-contents

我遇到了一个非常奇怪的问题。我在cURL上调用API。我收集了一些信息(请求,标题,响应,cookie等)然后如果测试模式打开,我最初会将它打印到浏览器。然后,在初始测试之后,我决定登录到文件,因此回显不会干扰ajax调用等。我使用file_get_contents / file_put_contents将日志保存到服务器上的文本文件中。但是当我这样做时,由于某种原因,卷曲请求被执行了两次!当我再次切换到echo时 - 它们只执行一次。防止双重调用的唯一另一种方法是,如果在发送页眉之前运行cURL函数,那么我会在???之后立即执行die()因此,当ajax运行时 - 没有双重调用。

例如,我遇到了一个接一个地运行两个API调用的情况。它们不会复制为A A B B,而是复制为A B A B。

我查了一下:

  • 类方法只被称为正确的次数(简单echo 'test';

  • curl_exec未在代码

  • 中重复
  • 删除保存到文件位会删除重复

以下是我的代码的两部分

CURL:

$headers= [
  'Content-Type: application/json',
  'Accept: application/json',
  'Api-Layer: '.$request['apilayer'],
];

$url = $this->server . $request['api'];

$ch = curl_init();      

$options = [
        CURLOPT_AUTOREFERER => TRUE,  
        CURLOPT_RETURNTRANSFER => TRUE, 
        CURLOPT_FOLLOWLOCATION => FALSE,    
        CURLOPT_HTTPHEADER => $headers,  
        CURLOPT_HEADER => TRUE,  
        CURLOPT_CONNECTTIMEOUT => 6,  
        CURLOPT_TIMEOUT => 6, 
];

$options[CURLOPT_POST] = TRUE;
$options[CURLOPT_POSTFIELDS] = $request['post'];
$options[CURLOPT_URL] = $url;

$cookies = [];
if (isset($_COOKIE['COOKIENAME'])) {
    $cookies[] = 'COOKIENAME ='.$_COOKIE['COOKIENAME'];
}

$options[CURLOPT_COOKIE] = implode(';', $cookies); 

curl_setopt_array($ch, $options); 
session_write_close();
$data = curl_exec($ch);
$curl_info = curl_getinfo($ch);     

$headers = substr($data, 0, $curl_info['header_size']);
$body = substr($data, $curl_info['header_size']);

curl_close($ch);
session_start();

preg_match('/Set-Cookie: COOKIENAME=([^\n;]*)\b/',$headers, $cookie1);
if (!empty($cookie1[1])) {
    $this->createCookie('COOKIENAME',$cookie1[1]);
}

$response = [
    'http_code' => $curl_info['http_code'],
    'body' => $body,
];

if ($this->test) {
    $this->addToLog($headers , 'RESPONSE_HEADERS');
    $this->addToLog($body, 'RESPONSE_BODY');
    $this->addToLog($curl_info, 'CURL_GETINFO');
}

return $response;

然后稍后打印日志:

public function printLog() {

    $file = PATH_TO_DIR.'api_log.txt';  
    $current = file_get_contents($file);
    $current .= $this->apiLog;
    file_put_contents($file, $current);
    $this->apiLog = '';
}

我缺少什么?

编辑:这可能是htaccess问题吗?我从bitnami运行常规MAMP堆栈

0 个答案:

没有答案