PHP: Find out who are not following you back programmatically for Instagram

I think it’s quite hard to find out if someone you are following but he or she aren’t, right? Or perhaps at least I have this problem. Instagram is not like Facebook which require two way relationships whenever you friend with someone. Unlike Twitter, Instagram does not supply information if the person is following you back or you are not following your followers back.

The screenshot below was the output of the code I tried for my Insta. If you don’t want to jump to the coding part you might try the final product of the codeĀ  here: http://sandbox.mahadirlab.com/instagram/ .

follower

To proceed you must have your Developer Account, first register from this link: http://instagram.com/developer/ after that, click Manage Client and Register New Client. The step is straight forward so I will not explain it step by step. Once you have registered your client, you should have the client_id and client_secret.

manage-client

The next step is our coding part:

The full code, I will explain some portion of the code. Make sure to change $redirect_uri, $client_id, and $client_secret according to your own settings.

[php]

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="Mahadir Ahmad" />

<title>Instagram’s One Way Relationship Finder</title>
</head>

<body>
<h2>By Madet</h2>
<?php

/**
* @author Mahadir Ahmad
* @copyright 2014
*/

set_time_limit(100);

$redirect_uri = "http://sandbox.mahadirlab.com/instagram";
$client_id = "6823c0b2…….";
$client_secret = "9558073………";

if (!isset($_GET[‘code’]))
{
$url = "https://instagram.com/oauth/authorize/?client_id=$client_id&redirect_uri=$redirect_uri&response_type=code&scope=likes+comments+relationships";
echo ‘<script language="javascript" type="text/javascript">’;
echo ‘window.location.href="’.$url.’";’;
echo ‘</script>’;
exit;

}

$code = strip_tags($_GET[‘code’]);

// get access token from the previous auth
$t = InstaGetAccToken($client_id, $client_secret, $redirect_uri, $code);

//verify if not success then exit with error
if($t == false){
echo "<a href=\"$redirect_uri\">Back</a><br>";
die("Access Code probably have been used!");
}

$id = $t[‘id’];
$token = $t[‘access_token’];

//followed-by
//follows
$following = JsonRelation($id, $token, "follows");
$follower = JsonRelation($id, $token, "followed-by");

//remove key that mathced both follower and following
//so the remaining are not have two ways relationship
foreach ($follower as $k => $v)
{
if (array_key_exists($k, $following))
{
unset($follower[$k]);
unset($following[$k]);
}
}

$counter = 0;
echo "<h1>I followed " . count($following) . " of them but they did’t O.0</h1>";
foreach ($following as $k => $v)
{
//Unfollow("42484815.1fb234f.ce7c49fd02b44a79a5f3b2cxxxxxxx",$id,$k);

echo "<td><img src=\"" . $v["profile_picture"] . "\" width=\"16px\" height=\"16px\"></td>\n";
echo "<td><a href=\"http://instagram.com/" . $v["username"] . "\">" . $v["username"] .
"</a></td>\n";

$counter++;
if ($counter == 10)
$counter = 0; //reset
if ($counter == 0)
echo "<br>\n";
}

$counter = 0;
echo "<h1>I didn’t follow " . count($follower) .
" of them but they did. Thanks, I’ll catch up :)</h1>";
foreach ($follower as $k => $v)
{
echo "<td><img src=\"" . $v["profile_picture"] . "\" width=\"16px\" height=\"16px\"></td>\n";
echo "<td><a href=\"http://instagram.com/" . $v["username"] . "\">" . $v["username"] .
"</a></td>\n";

$counter++;
if ($counter == 10)
$counter = 0; //reset
if ($counter == 0)
echo "<br>\n";
}

?>

</body>
</html>

<?php

/**
* @author Mahadir Ahmad
* @copyright 2014
* List of inline function
*/

/**
* Get Access token from authenticated user
* @return array of access_token and user’s id
*/
function InstaGetAccToken($client_id, $client_secret, $redirect_uri, $AuthCode)
{
$url = ‘https://api.instagram.com/oauth/access_token’;
$param = array(
‘client_id’ => $client_id,
‘client_secret’ => $client_secret,
‘grant_type’ => ‘authorization_code’,
‘redirect_uri’ => $redirect_uri,
‘code’ => $AuthCode);
$data = instaHttpRequest($url, $param, $type = ‘POST’, false);
$t = json_decode($data, 1);
if($t[‘code’] == 400)
return false;
else
return array("id" => $t[‘user’][‘id’], "access_token" => $t[‘access_token’]);
}

function JsonRelation($id, $token, $relation = "follows")
{
$url = "https://api.instagram.com/v1/users/$id/$relation?access_token=$token";
$data = json_decode(instaHttpRequest($url, ”, ‘GET’, false), 1);
$next_page = $data["pagination"]["next_url"];
$arr = array();

$i = 0;
//fetch all
while (1)
{

foreach ($data["data"] as $k1 => $val1)
{
$i++;

$arr += array($val1["id"] => array(
"username" => $val1["username"],
"profile_picture" => $val1["profile_picture"],
"number" => $i));
}

if (empty($next_page))
break;

$data = json_decode(instaHttpRequest($next_page, ”, ‘GET’, false), 1);
$next_page = $data["pagination"]["next_url"];
}

return $arr;
}

function Unfollow($token,$myid,$targetid){
$url = "https://api.instagram.com/v1/users/$myid/relationship?access_token=$token";
$param = array(
‘access_token’ => $token,
‘action’ => "unfollow",
);
$data = instaHttpRequest($url, $param, $type = ‘POST’, false);
$t = json_decode($data, 1);
if($t[‘meta’][‘code’] == 400)
return false;
else
return true;
}

function instaHttpRequest($url, $param, $type = ‘POST’, $debug = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

if ($debug === true)
{
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
}

if ($type == "POST")
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);

if ($debug === true)
{
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($data, 0, $header_size);
$body = substr($data, $header_size);
curl_close($ch);
echo "<pre>";
print_r($header);
echo "</pre>";
return $body;
}

curl_close($ch);
return $data;
}

?>
[/php]

The first part is to authenticate the user, they need to sign-in and redirected to Instagram login page.

A code will be returned back from the authentication and can be used to request access token to make certain API call. I have created the function for gaining the access token and user ID from InstaGetAccToken() .

The JsonRelation() function will return arrays of users following or follower of the ID passed to the function.

The formula or algorithm to separate the follower who are not following you back is simple, just compare the two arrays if the ID exist on both of followers and followings, remove it.

That’s all, I have also commented the source code with explanation.

Download: http://sandbox.mahadirlab.com/instagram/index.zip