Hamzeh Soboh
Hamzeh Soboh

Reputation: 7710

HTTP curl failed 403 but success with Guzzle

I'm trying to consume Instagram API for getting user feeds. With a normal curl I get 403, but it works fine using guzzle. I don't want to use a 3rd party. Any way to get it working with a curl?

This is my code:

const INSTAGRAM_ENDPOINT = 'https://www.instagram.com/';
const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36';
const QUERY_HASH = '42323d64886122307be10013ad2dcc44';

$variables = [
    'id' => '232192182',
    'first' => '12',
    'after' => 'AQCWAl5VxOspHxLFduBo0kmKu0ILD-jynobaAJQBvRz8S1Vu1rDpz5KnyTADU4hxyOyHAsnrF_8RYXOYIXgwzbdUO41D2rfzL-PZN26HABDtoQ' // $this->endCursor,
];
$endpoint = INSTAGRAM_ENDPOINT . 'graphql/query/?query_hash=' . QUERY_HASH . '&variables=' . json_encode($variables);

$hArray = [
    'User-Agent' => USER_AGENT,
    'X-Requested-With' => 'XMLHttpRequest',
    'X-Instagram-Gis' => 'cc2796cff28f2a3d71c73a4b61f62d84'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $hArray);
$server_output = curl_exec($ch);
curl_close($ch);
echo "<br>" . "<br>" . $server_output . "<br>" . "<br>";

Response:

HTTP/1.1 403 Forbidden Content-Type: text/html; charset=utf-8 x-robots-tag: noindex Cache-Control: private, no-cache, no-store, must-revalidate Pragma: no-cache Expires: Sat, 01 Jan 2000 00:00:00 GMT Vary: Cookie, Accept-Language Content-Language: en Date: Sat, 26 May 2018 09:22:28 GMT Strict-Transport-Security: max-age=86400 Set-Cookie: rur=FRC; Path=/ Set-Cookie: csrftoken=Vhh1ImCoyX1uMhfjZx65R9QbzewBsgzH; expires=Sat, 25-May-2019 09:22:28 GMT; Max-Age=31449600; Path=/; Secure Set-Cookie: mid=WwknVAAEAAFT3mN8ogObl6HSnQNy; expires=Fri, 21-May-2038 09:22:28 GMT; Max-Age=630720000; Path=/ Connection: keep-alive Content-Length: 0 

And the guzzle working code is:

$res = client->request('GET', $endpoint, ['headers' => $hArray]);
$data = (string)$res->getBody();

I can't get it working even with postman! So, what guzzle do extra stuff to make it work?

Update

Still need to get success with postman:

enter image description here

Upvotes: 0

Views: 798

Answers (1)

user8034901
user8034901

Reputation:

Your headers are not in the correct format. From PHPs curl_setopt page:

CURLOPT_HTTPHEADER An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')

Change your $hArray to this and you should be fine to go:

$hArray = [
    'User-Agent: '.USER_AGENT,
    'X-Requested-With: XMLHttpRequest',
    'X-Instagram-Gis: cc2796cff28f2a3d71c73a4b61f62d84'
];

Upvotes: 2

Related Questions