cURL PHP:将照片上传到Instagram

时间:2018-10-19 08:27:16

标签: php api curl file-upload

我授权使用Instagram,获取了所有cookie,等等。

现在是时候在https://www.instagram.com/create/upload/photo/发出请求了。

在Chrome的检查器中,我看到浏览器发送了这些发布数据(二进制照片可能是斑点):

upload_id: 1539936226445
photo: (binary)
media_type: 1

和自定义标题:

x-csrftoken: ACCESS_TOKEN_THAT_I_ALREADY_WROTE_INTO_THE_FILE
x-instagram-ajax: 723425780848
x-requested-with: XMLHttpRequest

但是当我使用cURL进行相同的请求(传递我在上面写的帖子和标头)时,我得到403禁止访问,但是应该得到200 Ok的JSON响应。

这是我发出请求的方式:

        $this->headers['csrftoken'] = $this->getFileData('csrftoken');
        // generate upload_id for post field
        $uploadId = number_format(round(microtime(true) * 1000), 0, '', ''); 
        // generate binary from image file (maybe not correct)          
        $file_bin = fopen($file, 'rb'); 

        // all my post fields
        $params = array(
            'upload_id' => $uploadId,
            'photo' => $file_bin,
            'media_type' => '1',
        );

        $ch = curl_init('https://www.instagram.com/create/upload/photo/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        // custom headers
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'x-csrftoken: '.$this->headers['csrftoken'],
            'x-instagram-ajax: '.$this->headers['x-instagram-ajax'],
            'x-requested-with: '.$this->headers['x-requested-with']
        ));

        curl_setopt($ch, CURLOPT_POST, true);
        // post fields
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
        // and finally get 403 forbidden instead of 200 ok with json response
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;

有人知道问题可以隐藏在哪里吗?

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您应该传递cookie数据,或在代码内启动另一个会话,然后发送cookie和该会话的csrftoken。

相关问题