Instagram API retrieves code using PHP

I'm trying to use the Instagram API, but it's really not easy.

According to the API documentation, the code needs to be fetched to get the access token and then make requests to the Instagram API.

But after several tries I fail.

I have already configured the settings well at

I call url[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code

with curl

, but I have no redirect uri

code in response.

Can you help me?)!


source to share

3 answers

I would recommend that you use one of the existing PHP scripting client libraries like



I did it not too long ago, here's a good link:

Let me know if it helps!



I made this code, hopefully it has no error, but I just did it for the usecase as you wanted. Here is the code, I will explain below how this code works.

$authorization_url = "".$instagram_client_id."&redirect_uri=".$your_website_redirect_uri."&response_type=code";
$_defaultHeaders = array(
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.5',
        'Accept-Encoding: ',
        'Connection: keep-alive',
        'Upgrade-Insecure-Requests: 1',
        'Cache-Control: max-age=0'
$ch  = curl_init();
            curl_setopt( $ch, CURLOPT_POST, 0 );
            curl_setopt( $ch, CURLOPT_HTTPGET, 1 );
                array_push($this->_defaultHeaders,"Authorization: ".$this->token);   
            curl_setopt( $ch, CURLOPT_HTTPHEADER, $this->_defaultHeaders);
            curl_setopt( $ch, CURLOPT_HEADER, true);
            curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch, CURLOPT_COOKIEFILE,getcwd().$cookie );
            curl_setopt( $ch, CURLOPT_COOKIEJAR, getcwd().$cookie );

            $result = curl_exec($this->curlHandle);
            $redirect_uri = curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL);
            $form = explode('login-form',$result)[1];
        $form = explode("action=\"",$form)[1];
//        vd('asd',$form);
        $action = substr($form,0,strpos($form,"\""));
//        vd('action',$action);
        $csrfmiddlewaretoken = explode("csrfmiddlewaretoken\" value=\"",$form);
        $csrfmiddlewaretoken = substr($csrfmiddlewaretoken[1],0,strpos($csrfmiddlewaretoken[1],"\""));
        //finish getting parameter

//format instagram cookie from vaha answer
    preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);

    $cookieFileContent = '';

    foreach($matches[1] as $item)
        $cookieFileContent .= "$item; ";

    $cookieFileContent = rtrim($cookieFileContent, '; ');
    $cookieFileContent = str_replace('sessionid=; ', '', $cookieFileContent);
    $oldContent = file_get_contents($cookie);
    $oldContArr = explode("\n", $oldContent);
        foreach($oldContArr as $k => $line)
            if(strstr($line, '# '))

        $newContent = implode("\n", $oldContArr);
        $newContent = trim($newContent, "\n");

    // end format
    $useragent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0";
    $arrSetHeaders = array(
        'upgrade-insecure-requests: 1',
        "User-Agent: $useragent",
        'content-type: application/x-www-form-urlencoded',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.5',
        'Accept-Encoding: deflate, br',
        "Referer: $redirect_uri",
        "Cookie: $cookieFileContent",
        'Connection: keep-alive',
        'cache-control: max-age=0',

    $ch  = curl_init();
    curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__)."/".$cookie);
    curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/".$cookie);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $arrSetHeaders);
    curl_setopt($ch, CURLOPT_URL, $this->base_url.$action);
    curl_setopt($ch, CURLOPT_REFERER, $redirect_uri);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_param));

    $page = curl_exec($ch);

    preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $page, $matches);
    $cookies = array();
    foreach($matches[1] as $item) {
        parse_str($item, $cookie1);
        $cookies = array_merge($cookies, $cookie1);


Step 1: First, we need to go to the login page.
We can access it using curl get, with CURLOPT_FOLLOWLOCATION

set to true so that we are redirected to the login page and we can access our application authorization url.

$authorization_url = "".$instagram_client_id."&redirect_uri=".$your_website_redirect_uri."&response_type=code";


This is step one of this Instagram documentation here
Now the result of the first get curl we have a response page and its page uri which we store in $ redirect_uri, this must be needed and put in the referer header when we make an http post to login.

After getting the login_page result, we need to format the cookie, I know this and using the code from vaha here vaha's answer

Step 2: After we get the login_page, we fetch the action url, extract the csrfmiddlewaretoken

hidden input.
After we get it, we will enter the parameter to enter. We have to set the uri redirect and not forget the cookiejar and other header settings like above code.
After successfully sending the login parameter message, Instagram will trigger your uri redirect, for example

where you should use or save the instagram code to get the access token using curl again (I will only explain how to get the code: D)
I will do it for in a short time, I will update the code I tested and work, if I have time, feel free to suggest editing a workable code or a better explanation.



All Articles