cURL在一台服务器上保存cookie,但不会在另一台服务器上保存cookie

时间:2016-02-04 00:43:00

标签: php api curl cookies

我以前从未使用过cURL而且遇到了问题。

我正在编写一个小的PHP脚本来与Dotcom Monitor's API

进行交互

我正在使用他们的example code from here发出API请求,我已将其转换为此函数(在PHP类中):

private function Request($action, $method, $data)
    {
        /**
         * Retrieves data from Dotcom Monitor API
         * @param string $action - dynamic url part
         * @param string $method - HTTP method POST/GET
         * @param string $data - POST data, 'null' for GET request, json_encode() is called on this param
         * @return stdClass object The response to the request
         */
        // setting request url (merging "constant" and "dynamic" part)
        $ch = curl_init($this->API_URL . $action);
        // setting HTTP method
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        // return string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // ignoring SSL certificate
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // Cookie management
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
        // creating request header array
        $headers = array('Content-Type: application/json');
        // checking if 'POST' method
        if($method === 'POST' && $data != null)
        {
            // encode input data to json
            $data_string = json_encode($data);
            // setting POST data
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            // setting content length header
            array_push($headers, 'Content-Length: ' . strlen($data_string));
        }
        // setting headers
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // making request
        $result = curl_exec($ch);
        // closing connection
        curl_close($ch);
        // returning deserialized json data as object
        return json_decode($result);
    }

我正在调用这样的函数:

$login = $this->Request('login', "POST", $this->$API_CREDENTIALS);

API的工作方式是,

  • 您登录(通过上述电话)
  • 您已通过身份验证
  • Cookie存储在cookie.txt
  • 认证有效期为60秒
  • 对API的每次后续调用都会重新启动60秒计时器

我在我自己的服务器上使用它,一切正常,我登录后,创建了cookie文件,后续调用API读取cookie并允许这些调用。

我可以在phpFiddle上运行它,一切都很完美(完全如上)。

问题:

然而,当我在我的工作服务器上上传完全相同的代码时,登录调用成功,但cookie.txt 创建,这似乎无声地使所有API调用失败登录。

到目前为止我检查了什么:

  • 不会抛出任何PHP错误(启用错误报告)
  • 在服务器上启用了cURL
  • 在服务器上启用了cookie
  • 有问题的文件夹是apache / web writable

服务器信息

工作服务器:

  • 配置 - apc版本3.1.13
  • PHP Version 5.4.19
  • 启用了cURL支持
  • cURL信息7.19.7

非工作服务器:

  • 配置 - apache2handler Apache版本Apache / 2.4.6(CentOS)OpenSSL / 1.0.1e-fips PHP / 5.4.16
  • PHP版本5.4.16
  • 启用了cURL支持
  • cURL信息7.29.0
  • Apache Version Apache / 2.4.6(CentOS)OpenSSL / 1.0.1e-fips PHP / 5.4.16

2 个答案:

答案 0 :(得分:1)

您需要定义此文件的完整(绝对)路径。

b=a

答案 1 :(得分:0)

在网络服务器具有写入权限的目录中提供cookies.txt的完整路径。例如/tmp/cookies.txt

相关问题