Search code examples
javascriptphpcurlinstagraminstagram-api

X-Insta-Forwarded-For Error Instagram API using PHP cURL


I'm trying to make a post to instagram using this api and the POST method of relationships.

Here is the side-server code I'm using:

<?php

$url = "https://api.instagram.com/v1/users/<user>/relationship";
$ips= (isset($_SERVER['SERVER_ADDR'])) ? $_SERVER['SERVER_ADDR'] : gethostbyname(gethostname());
$signature = (hash_hmac('sha256', $ips, '<secret>', false));

$join = join('|', array($ips, $signature));

$headerData = array('Accept: application/json');

$headerData[] = 'X-Insta-Forwarded-For: ' .$join;

$fields = array(
        'access_token'       =>      '<access_token>',
        'action'             =>      'follow'
    );

$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $headerData);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

// grab URL and pass it to the browser
$result = curl_exec($ch);
$error = curl_error($ch);
// close cURL resource, and free up system resources
curl_close($ch);

print_r($result);
?>

AS you can see I have this line commented out:

//curl_setopt($ch, CURLOPT_HTTPHEADER, $headerData);

Because as I know, to POST to instagram using cURL I only need a valid access_token, but Instagram is returning me this error:

{"code": 403, "error_type": "OAuthForbiddenException", "error_message": "Invalid header: X-Insta-Forwarded-For is required for this operation"}

I understand what this means, but my question is if someone has tried something similar without registering an app on Instagram API and using an external access_token found on internet?


Solution

  • The access_token you are using belongs to an app that probably has this signed header POST restriction active ("Enforce signed header").

    Go to https://instagram.com/developer/clients/manage/ to create or manage your apps, click on Edit app and then on Security tab. You should see the page below. Enforce signed requests (the new and better signing method) and Enforce signed header (the old one, that will be deprecated on September 1th) are the methods to avoid misuse of stolen access_token.

    You can't post anything to Instagram API without X-Insta-Forwarded-For if Enforce signed header is checked. Just as you can't make a request to API without the sig parameter if "Enforce signed requests" is checked.

    I recommend you learn the new signed request method observing those Instagram API secure requests considerations

    Instagram App Security Tab