PHP Instagram Photo Downloader

+18 Bucky Roberts · July 15, 2014
Just configure lines 12-15 with your Instagram API Info and you are good to go :)
<?php

//first create a developer account and register a new client


set_time_limit(0); //script will run for an infinite amount of time
ini_set('default_socket_timeout', 300); //server settings
session_start(); //starts new or resume existing session


/*-------- CONFIGURE THESE --- Instagram API KEYS --------*/
define("clientID"       , ''); //associated your developer account with this program
define("clientSecret"   , ''); //password
define("redirectURI"    , ''  ); //after users choose whether to let you use access account or not (must match the one you registered)
define("imageDirectory" ,    'pics/'); //make sure to create this directory on your server

 
//Connect with Instagram
function connectToInstagram($url){
$ch = curl_init(); //used to transfer data with a url

curl_setopt_array($ch, array( //sets options for a curl transfer
CURLOPT_URL => $url, //the url
CURLOPT_RETURNTRANSFER => true, //return the results if successful
CURLOPT_SSL_VERIFYPEER => false, //we dont need to verify any certificates
CURLOPT_SSL_VERIFYHOST => 2 //we wont verify host
));

$result = curl_exec($ch); //executue the transfer
curl_close($ch); //close the curl session
return $result; //returns all the data we gathered
}


//Get Instagram userID
function getUserID($userName){
$url = 'https://api.instagram.com/v1/users/search?q='. $userName .'&client_id='. clientID;
$instagramInfo = connectToInstagram($url);
$results = json_decode($instagramInfo, true); //takes a JSON encoded string and converts it into a PHP variables

return $results['data'][0]['id']; //returns the userID
}


//Print out the images
function printImages($userID){
$url = 'https://api.instagram.com/v1/users/'. $userID .'/media/recent?client_id='. clientID .'&count=5';
$instagramInfo = connectToInstagram($url);
$results = json_decode($instagramInfo, true);

//parse through results
foreach($results['data'] as $item){
$image_url = $item['images']['low_resolution']['url'];
echo '<img src="'.$image_url.'" /> <br/>';
savePicture($image_url);
}
}


//Save the Picture
function savePicture($image_url){
echo $image_url . '<br />';
$filename = basename($image_url);
echo $filename . '<br />';
//SELECT * FROM pics WHERE filename=$filename ---- if no matches, continue
$destination = imageDirectory.$filename;
file_put_contents($destination, file_get_contents($image_url));
}


//Get user code and save info to session variables
if($_GET['code']){
$code = $_GET['code'];
$url = "https://api.instagram.com/oauth/access_token";
$access_token_settings = array(
'client_id'                =>     clientID,
'client_secret'            =>     clientSecret,
'grant_type'               =>     'authorization_code',
'redirect_uri'             =>     redirectURI,
'code'                     =>     $code
);
$curl = curl_init($url);     //we need to transfer some data
curl_setopt($curl,CURLOPT_POST,true);   //using POST
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_settings);   //use these settings
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   //return results as string
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);   //don't need to verify any certificates
$result = curl_exec($curl);   //go get the data!
curl_close($curl);   //close connection to free up your resources

$results = json_decode($result,true);

$userName = $results['user']['username'];
$userID = getUserID($userName);
printImages($userID);

}else{ ?>


<!doctype html>
<html lang="en">
<body>
<!-- When they click this, they will be prompted to Login to Instagram -->
<a href="https://api.instagram.com/oauth/authorize/?client_id=<?php echo clientID; ?>&redirect_uri=<?php echo redirectURI; ?>&response_type=code">Login</a>
</body>
</html>

<?

}  


?>

Post a Reply

Replies

- page 1
Oldest  Newest  Rating
0 Himanshu Gupta · December 22, 2016
Guys I copied the code, but it isn't working. Please help!
Thanks. 
0 juan campos · March 7, 2016
connectToInstagram return null
+1 Captain Bacon · February 5, 2016
I am having the following Error within the loop...


Warning: Invalid argument supplied for foreach() in ../index.php on line 52

I don't understand too much whats going on... Any advices?
0 acemary mary · February 4, 2016
It's the overflow-like buttons (... next to the comment and like buttons)

Using a long press on the image might cause the user to unintentionally like a photo by mistake, so I opted for that instead.    http://www.traininginsholinganallur.in/php-training-in-chennai.html  |    http://www.traininginsholinganallur.in/web-designing-training-in-chennai.html
0 Robertas Micius · February 4, 2016
You can download easily with inspect code and find whats the link to image :D 
+1 Umair Qamar · February 3, 2016
Instagram Updated its API and there are some changes you need to make in order to make this application run.

  • There is no need of function getUserId we can get it like
    $userName = $results['user']['username'];
    $userID = $results['user']['id'];


  • All API endpoints require a valid access_token, So i too access token from $results array like this

  • $accessToken = $results['access_token'];and passed it to printImages function,also the url to print Images is also updatedFollowing is the complete wordking code<?php//first create a developer account and register a new clientset_time_limit(0); //script will run for an infinite amount of timeini_set('default_socket_timeout', 300); //server settingssession_start(); //starts new or resume existing session/*-------- CONFIGURE THESE --- Instagram API KEYS --------*/ define("clientID"       , ''); //associated your developer account with this programdefine("clientSecret"   , ''); //passworddefine("redirectURI"    , ''  ); //after users choose whether to let you use access account or not (must match the one you registered)define("imageDirectory" ,    'pics/'); //make sure to create this directory on your server  //Connect with Instagramfunction connectToInstagram($url){ $ch = curl_init(); //used to transfer data with a url curl_setopt_array($ch, array( //sets options for a curl transfer CURLOPT_URL => $url, //the url CURLOPT_RETURNTRANSFER => true, //return the results if successful CURLOPT_SSL_VERIFYPEER => false, //we dont need to verify any certificates CURLOPT_SSL_VERIFYHOST => 2 //we wont verify host )); $result = curl_exec($ch); //executue the transfer curl_close($ch); //close the curl session return $result; //returns all the data we gathered}//Print out the imagesfunction printImages($userID,$accessToken){ $url = 'https://api.instagram.com/v1/users/'. $userID .'/media/recent?access_token='. $accessToken .'&count=5'; $instagramInfo = connectToInstagram($url); $results = json_decode($instagramInfo, true); //parse through results foreach($results['data'] as $item){ $image_url = $item['images']['low_resolution']['url']; echo '<img src="'.$image_url.'" /> <br/>'; savePicture($image_url); }}//Save the Picturefunction savePicture($image_url){ echo $image_url . '<br />'; $filename = basename($image_url); echo $filename . '<br />'; //SELECT * FROM pics WHERE filename=$filename ---- if no matches, continue $destination = imageDirectory.$filename; file_put_contents($destination, file_get_contents($image_url));}//Get user code and save info to session variablesif(isset($_GET['code'])){ $code = $_GET['code']; $url = "https://api.instagram.com/oauth/access_token"; $access_token_settings = array( 'client_id'                =>     clientID, 'client_secret'            =>     clientSecret, 'grant_type'               =>     'authorization_code', 'redirect_uri'             =>     redirectURI, 'code'                     =>     $code ); $curl = curl_init($url);     //we need to transfer some data curl_setopt($curl,CURLOPT_POST,true);   //using POST curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_settings);   //use these settings curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   //return results as string curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);   //don't need to verify any certificates $result = curl_exec($curl);   //go get the data! curl_close($curl);   //close connection to free up your resources $results = json_decode($result,true); $userName = $results['user']['username'];        $userID = $results['user']['id'];        $accessToken = $results['access_token']; printImages($userID,$accessToken); }else{ ?><!doctype html><html lang="en"><body> <!-- When they click this, they will be prompted to Login to Instagram --> <a href="https://api.instagram.com/oauth/authorize/?client_id=<?php echo clientID; ?>&redirect_uri=<?php echo redirectURI; ?>&response_type=code">Login</a></body></html><?php}  ?>
+1 Bronson Shonk · January 20, 2016
I am trying to make this work on my hosting service (bluehost) and not having any luck.  

The login works and I can get as far as printing out the username, but as soon as I start trying the functions I cannot see any results.

application is here:  http://www.tableart.co/other/instagram_test/index.php

I am using the exact code from above with my account information in lines 12 through 15.  

Any ideas?
0 sean mulder · October 22, 2015
Hi, the foreach loop gives me an error. Im not sure how to fix it. It's from the code above.

foreach ($results['data'] as $items) {

$image_url = $items['images']['low_resolution']['url'];
echo '<img src="' . $image_url . ' " />';
savePicture($image_url);
}

Warning: Invalid argument supplied for foreach() in /home/instayrk/public_html/index.php on line 63

Would appreciate any help
0 Kenneth Meadows II · July 6, 2015
I think I made an error in my code.  Would I be better off trying to get help in this comment section or starting a new thread?
0 william appiah-dankwah · July 17, 2014
Someone's been doing this to one of my Instagram accounts
  • 1
  • 2

PHP

124,602 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators