A PHP wrapper for the Instagram API. Feedback or bug reports are appreciated.

Overview

Image Instagram PHP API V2

Note: On the 17 Nov 2015 Instagram made changes to their API . Apps created before Nov 17, 2015 wont be affected until Jun 2016. Apps created on or after Nov 17 2015 will require to use their updated API. Please note that this library doesn't yet support their new updates. For more information, please see #182.

A PHP wrapper for the Instagram API. Feedback or bug reports are appreciated.

Total Downloads Latest Stable Version License

Composer package available.
Supports Instagram Video and Signed Header.

Requirements

  • PHP 5.3 or higher
  • cURL
  • Registered Instagram App

Get started

To use the Instagram API you have to register yourself as a developer at the Instagram Developer Platform and create an application. Take a look at the uri guidelines before registering a redirect URI. You will receive your client_id and client_secret.


Please note that Instagram mainly refers to »Clients« instead of »Apps«. So »Client ID« and »Client Secret« are the same as »App Key« and »App Secret«.


A good place to get started is the example project.

Installation

I strongly advice using Composer to keep updates as smooth as possible.

$ composer require cosenary/instagram

Initialize the class

Login with Instagram";">
use MetzWeb\Instagram\Instagram;

$instagram = new Instagram(array(
	'apiKey'      => 'YOUR_APP_KEY',
	'apiSecret'   => 'YOUR_APP_SECRET',
	'apiCallback' => 'YOUR_APP_CALLBACK'
));

echo "Login with Instagram";

Authenticate user (OAuth2)

// grab OAuth callback code
$code = $_GET['code'];
$data = $instagram->getOAuthToken($code);

echo 'Your username is: ' . $data->user->username;

Get user likes

// set user access token
$instagram->setAccessToken($data);

// get all user likes
$likes = $instagram->getUserLikes();

// take a look at the API response
echo '
';
print_r($likes);
echo '
';

All methods return the API data json_decode() - so you can directly access the data.

Available methods

Setup Instagram

new Instagram( / );

array if you want to authenticate a user and access its data:

new Instagram(array(
	'apiKey'      => 'YOUR_APP_KEY',
	'apiSecret'   => 'YOUR_APP_SECRET',
	'apiCallback' => 'YOUR_APP_CALLBACK'
));

string if you only want to access public data:

new Instagram('YOUR_APP_KEY');

Get login URL

getLoginUrl( )

getLoginUrl(array(
	'basic',
	'likes'
));

Optional scope parameters:

Scope Legend Methods
basic to use all user related methods [default] getUser(), getUserFeed(), getUserFollower() etc.
relationships to follow and unfollow users modifyRelationship()
likes to like and unlike items getMediaLikes(), likeMedia(), deleteLikedMedia()
comments to create or delete comments getMediaComments(), addMediaComment(), deleteMediaComment()

Get OAuth token

getOAuthToken($code, / )

true : Returns only the OAuth token
false [default] : Returns OAuth token and profile data of the authenticated user

Set / Get access token

  • Set the access token, for further method calls: setAccessToken($token)
  • Get the access token, if you want to store it for later usage: getAccessToken()

User methods

Public methods

  • getUser($id)
  • searchUser($name, <$limit>)
  • getUserMedia($id, <$limit>)

Authenticated methods

  • getUser()
  • getUserLikes(<$limit>)
  • getUserFeed(<$limit>)
  • getUserMedia(<$id>, <$limit>)
    • if an $id isn't defined or equals 'self', it returns the media of the logged in user

Sample responses of the User Endpoints.

Relationship methods

Authenticated methods

  • getUserFollows($id, <$limit>)
  • getUserFollower($id, <$limit>)
  • getUserRelationship($id)
  • modifyRelationship($action, $user)
    • $action : Action command (follow / unfollow / block / unblock / approve / deny)
    • $user : Target user id
// Follow the user with the ID 1574083
$instagram->modifyRelationship('follow', 1574083);

Please note that the modifyRelationship() method requires the relationships scope.


Sample responses of the Relationship Endpoints.

Media methods

Public methods

  • getMedia($id)
    • authenticated users receive the info, whether the queried media is liked
  • getPopularMedia()
  • searchMedia($lat, $lng, <$distance>, <$minTimestamp>, <$maxTimestamp>)
    • $lat and $lng are coordinates and have to be floats like: 48.145441892290336,11.568603515625
    • $distance : Radial distance in meter (default is 1km = 1000, max. is 5km = 5000)
    • $minTimestamp : All media returned will be taken later than this timestamp (default: 5 days ago)
    • $maxTimestamp : All media returned will be taken earlier than this timestamp (default: now)

Sample responses of the Media Endpoints.

Comment methods

Public methods

  • getMediaComments($id)

Authenticated methods

  • addMediaComment($id, $text)
    • restricted access: please email apidevelopers[at]instagram.com for access
  • deleteMediaComment($id, $commentID)
    • the comment must be authored by the authenticated user

Please note that the authenticated methods require the comments scope.


Sample responses of the Comment Endpoints.

Tag methods

Public methods

  • getTag($name)
  • getTagMedia($name)
  • searchTags($name)

Sample responses of the Tag Endpoints.

Likes methods

Authenticated methods

  • getMediaLikes($id)
  • likeMedia($id)
  • deleteLikedMedia($id)

How to like a Media: Example usage Sample responses of the Likes Endpoints.

All <...> parameters are optional. If the limit is undefined, all available results will be returned.

Instagram videos

Instagram entries are marked with a type attribute (image or video), that allows you to identify videos.

An example of how to embed Instagram videos by using Video.js, can be found in the /example folder.


Please note: Instagram currently doesn't allow to filter videos.


Signed Header

In order to prevent that your access tokens gets stolen, Instagram recommends to sign your requests with a hash of your API secret, the called endpoint and parameters.

  1. Activate "Enforce Signed Header" in your Instagram client settings.
  2. Enable the signed-header in your Instagram class:
$instagram->setSignedHeader(true);
  1. You are good to go! Now, all your requests will be secured with a signed header.

Go into more detail about how it works in the Instagram API Docs.

Pagination

Each endpoint has a maximum range of results, so increasing the limit parameter above the limit won't help (e.g. getUserMedia() has a limit of 90).

That's the point where the "pagination" feature comes into play. Simply pass an object into the pagination() method and receive your next dataset:

$photos = $instagram->getTagMedia('kitten');

$result = $instagram->pagination($photos);

Iteration with do-while loop.

Samples for redirect URLs

Registered Redirect URI Redirect URI sent to /authorize Valid?
http://yourcallback.com/ http://yourcallback.com/ yes
http://yourcallback.com/ http://yourcallback.com/?this=that yes
http://yourcallback.com/?this=that http://yourcallback.com/ no
http://yourcallback.com/?this=that http://yourcallback.com/?this=that&another=true yes
http://yourcallback.com/?this=that http://yourcallback.com/?another=true&this=that no
http://yourcallback.com/callback http://yourcallback.com/ no
http://yourcallback.com/callback http://yourcallback.com/callback/?type=mobile yes

If you need further information about an endpoint, take a look at the Instagram API docs.

Example App

Image

This example project, located in the example/ folder, helps you to get started. The code is well documented and takes you through all required steps of the OAuth2 process. Credit for the awesome Instagram icons goes to Ricardo de Zoete Pro.

More examples and tutorials:

Let me know if you have to share a code example, too.

Changelog

Please see the changelog file for more information.

Credits

Copyright (c) 2011-2015 - Programmed by Christian Metz

Released under the BSD License.

Comments
  • Instagram Platform Update

    Instagram Platform Update

    On the 17 Nov 2015 Instagram made changes to their API. Apps created before Nov 17, 2015 wont be affected until Jun 2016. Apps created on or after Nov 17 2015 will require to use their updated API. Please note that this library doesn't yet support their new updates.

    When we launched our first Instagram API in 2011, we were a very small team and knew we wouldn’t be able to build all the features our community might want. Today we are announcing several platform changes to improve people’s control over their content and set up a more sustainable environment built around authentic experiences on the platform… http://developers.instagram.com/post/133424514006/instagram-platform-update

    I guess we need to rethink this entire library in order to work with the latest changes. This will require a lot of efforts and there is currently no plan to update this library.


    If you're just looking for a simple way to fetch a public Instagram feed, you can checkout this package: vinkla/instagram.

    New feature 
    opened by vinkla 45
  • Enforce signed requests

    Enforce signed requests

    There is a new security mechanism in town:

    http://developers.instagram.com/post/116410697261/publishing-guidelines-and-signed-requests

    Don't know, if the old system with signed headers is fully deprecated.

    Documentation of the feature: https://instagram.com/developer/secure-api-requests/

    New feature Optimization 
    opened by johannesnagl 14
  • request

    request

    Hello excuse me. my English writing is bad. i need a forced SIGNED key that have permission of like. instagram policy have been changed. and new public app can not access to like endpoint. Link(http://developers.instagram.com/post/116410697261/publishing-guidelines-and-signed-requests) do you have any key with permission of like? i can buy it from you .( or i can give 15% of my sell to you .) if you give me a key with like permission

    i promise you that i use it only in my application. and my application is valid in (TERMS OF USE) of instagram.

    please reply to my message for more speeking about it.

    thanks.

    opened by bagvand 13
  • modifyRelationship not working?

    modifyRelationship not working?

    Hi, I've been using your instagram API and thanks for putting it up.

    Now I'm working at the stage where I can follow/unfollow users.

    However when I tried the simple example given

    $instagram->modifyRelationship('follow', 1574083);

    it doesn't work.

    do you mind showing me how your modifyRelationship func works?

    Cheers.

    opened by ViktorShinova 10
  • Pagination?

    Pagination?

    Hi, I've been working with your wrapper for a while now (thanks so much for it!) and I've been trying to figure out a pagination method but couldn't figure it out! the example you used in the docs don't work either... the $instagram->pagination()...

    Any ideas?

    opened by tdunham02 10
  • Pagination Feedback

    Pagination Feedback

    Hi Christian,

    Good job on this class!

    A few thoughts on the alpha pagination method.

    We found that the current method was quite restrictive because you're having to pass the entire response from a previous call.

    Instead, would it be better to just be able to pass the next_max_id into the method?

    So the PHP method would simply be like this (Ignore the naming convention)

      public function paginationById($next_max_id) {
        if (true === is_int($next_max_id) ) {
          return $this->_makeCall($function, $auth, array('max_id' => $next_max_id));
        } else {
          throw new Exception("Error: pagination() | Pagination doesn't support this paramater type.");
        }
      }
    
    opened by adamstrawson 9
  • Add X-RateLimit-Remaining API

    Add X-RateLimit-Remaining API

    When calling the instagram API, you're limited to 5000 calls per hour per token. It would be very useful if your class/code had an attribute that stored that info so I could keep track of where my users are in their current hour's limit.

    Is there a call to be made that will give the current limit without expending 1 call? Doesn't seem like it.

    New feature 
    opened by gmisura 8
  • The access_token provided is invalid

    The access_token provided is invalid

    I successfully can get the media by tags with my access_token using link at below:

    (https://api.instagram.com/v1/tags/qe/media/recent?access_token=MY_TOKEN)
    

    But, while using this api, i receive an error: The access_token provided is invalid

    Here is my code:

    $instagram = new Instagram($client_id); //
    $instagram->setAccessToken($my_token);
    $tags = $instagram->getTag("qe");
    

    What is wrong in my code?

    opened by aghayeff 7
  • Unspecified $limit parameters cause API to return error

    Unspecified $limit parameters cause API to return error

    Recent updates to the API require that count > 0 when calling search/user. Current code documentation suggests that $limit is optional, but the default $limit value is always passed to the API regardless. Since the API now won't accept 0 as a valid value, it returns an error. To maintain backwards compatibility, this change passes the count value to the API if and only if it has been explicitly set when calling searchUser().

    This same pattern (unspecified $limit then turning into an explicit value for count when calling the API) exists for a number of other methods as well. To maintain consistency, the other affected methods which take $limit as an "optional" parameter have been modified to follow the same convention.

    Bug 
    opened by ahojchris 6
  • Further errors in localhost - wamp

    Further errors in localhost - wamp

    When I try running the example in my wamp localhost I get: ( ! ) Fatal error: Uncaught exception 'Exception' with message 'Error: _makeCall() - cURL error: Problem (2) in the Chunked-Encoded data' in C:\wamp\www\insta\example\instagram.class.php on line 454 ( ! ) Exception: Error: _makeCall() - cURL error: Problem (2) in the Chunked-Encoded data in C:\wamp\www\insta\example\instagram.class.php on line 454

    If I comment out the line that throws the exception above I'm then greeted by this: ( ! ) Notice: Trying to get property of non-object in C:\wamp\www\insta\example\success.php on line 68 ( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\insta\example\success.php on line 68

    I've already added these to lines to the _makeCall function: curl__setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    Any help would be much appreciated.

    opened by C-onnor 6
  • Receiving: Notice: Undefined property: stdClass

    Receiving: Notice: Undefined property: stdClass

    This is my first time working with cosenary. So far, good. But when I try to autenticate access some private methods I receive "Notice: Undefined property: stdClass" when I call "setAccessToken". Here is some sample code:

    getOAuthToken($code, true); $_SESSION['access_token'] = $token; $instagram->setAccessToken($token); ?>

    Any help?

    Thanks

    opened by esteban1972 5
  • Trying to get in touch regarding a security issue

    Trying to get in touch regarding a security issue

    Hey there!

    I'd like to report a security issue but cannot find contact instructions on your repository.

    If not a hassle, might you kindly add a SECURITY.md file with an email, or another contact method? GitHub recommends this best practice to ensure security issues are responsibly disclosed, and it would serve as a simple instruction for security researchers in the future.

    Thank you for your consideration, and I look forward to hearing from you!

    (cc @huntr-helper)

    opened by JamieSlome 0
  • Security Fix for Cross-site Scripting (XSS) - huntr.dev

    Security Fix for Cross-site Scripting (XSS) - huntr.dev

    https://huntr.dev/users/Mik317 has fixed the Cross-site Scripting (XSS) vulnerability 🔨. Mik317 has been awarded $25 for fixing the vulnerability through the huntr bug bounty program 💵. Think you could fix a vulnerability like this?

    Get involved at https://huntr.dev/

    Q | A Version Affected | ALL Bug Fix | YES Original Pull Request | https://github.com/418sec/Instagram-PHP-API/pull/2 Vulnerability README | https://github.com/418sec/huntr/blob/master/bounties/packagist/instagram-php-api/1/README.md

    User Comments:

    📊 Metadata *

    Bounty URL: https://www.huntr.dev/bounties/1-packagist-instagram-php-api

    ⚙️ Description *

    An XSS issue occured in the instagram-php-api project, which was due to insecure reflection of usersupplied input through the ?error_description parameter.

    💻 Technical Description *

    I used the htmlentities() method to sanitize the malicious parameter, avoiding the issue aforementioned.

    🐛 Proof of Concept (PoC) *

    No POC, but the issue was clear by the code

    🔥 Proof of Fix (PoF) *

    No POC, but htmlentities() works fine with every scenario

    👍 User Acceptance Testing (UAT)

    Just used htmlentities() on a string

    opened by huntr-helper 0
  • Does this library still work?

    Does this library still work?

    Based on the breaking changes of the Instagram API on June 29, 2020:

    The remaining Instagram Legacy API permission ("Basic Permission") was disabled on June 29, 2020. As of June 29, third-party apps no longer have access to the Legacy API.

    More info here: https://www.instagram.com/developer/

    @cosenary, this library is no longer working.

    opened by skillmatic-co 1
  • i can't login.

    i can't login.

    i took app_secret key and app_id, wrote this codes but when i clicked Login with instagram, i take 'Oops, an error occurred.' error in page.

    help please.

    opened by ozgurkaracam 1
An object oriented PHP wrapper for the Livepeer API

Livepeer PHP An object oriented PHP wrapper for the Livepeer API Requirements PHP >= 7.4 A PSR-17 implementation A PSR-18 implementation Install Via C

Owen Voke 2 Nov 23, 2021
Zoho CRM API SDK is a wrapper to Zoho CRM APIs. By using this sdk, user can build the application with ease

Archival Notice: This SDK is archived. You can continue to use it, but no new features or support requests will be accepted. For the new version, refe

null 81 Nov 4, 2022
💗 C++ wrapper for Zend API

PHP-X C++ wrapper for Zend API Requirements PHP 7.2 or later Linux/MacOS/Windows GCC 4.8 or later Composer Build phpx (bin) ./build.sh sudo cp bin/php

韩天峰-Rango 815 Dec 6, 2022
Simple and effective multi-format Web API Server to host your PHP API as Pragmatic REST and / or RESTful API

Luracast Restler ![Gitter](https://badges.gitter.im/Join Chat.svg) Version 3.0 Release Candidate 5 Restler is a simple and effective multi-format Web

Luracast 1.4k Dec 14, 2022
An easy to use Fractal wrapper built for Laravel and Lumen applications

An easy to use Fractal wrapper built for Laravel and Lumen applications The package provides a nice and easy wrapper around Fractal for use in your La

Spatie 1.8k Dec 30, 2022
Laravel wrapper for Facebook's GraphQL

Laravel GraphQL Use Facebook's GraphQL with Laravel 6.0+. It is based on the PHP port of GraphQL reference implementation. You can find more informati

Mikk Mihkel Nurges 1.9k Dec 31, 2022
微信支付 API v3 的 PHP Library,同时也支持 API v2

微信支付 WeChatPay OpenAPI SDK [A]Sync Chainable WeChatPay v2&v3's OpenAPI SDK for PHP 概览 微信支付 APIv2&APIv3 的Guzzle HttpClient封装组合, APIv2已内置请求数据签名及XML转换器,应

null 275 Jan 5, 2023
Simple PHP API client for tube-hosting.com rest API

Tube-Hosting API PHP client Explanation This PHP library is a simple api wrapper/client for the tube-hosting.com api. It is based on the provided docu

null 4 Sep 12, 2022
Chargebee API PHP Client (for API version 2 and Product Catalog version 2.0)

chargebee-php-sdk Overview This package provides an API client for Chargebee subscription management services. It connects to Chargebee REST APIs for

GLOBALIS media systems 8 Mar 8, 2022
This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science courses and the like.

Simple PHP API v.1.0 This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science courses a

Edson M. de Souza 14 Nov 18, 2021
This API provides functionality for creating and maintaining users to control a simple To-Do-List application. The following shows the API structure for users and tasks resources.

PHP API TO-DO-LIST v.2.0 This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science cours

Edson M. de Souza 6 Oct 13, 2022
API documentation API SCB EASY APP

SCB-API-EASY V3.0 API documentation SIAM COMMERCIAL BANK PUBLIC COMPANY LTD. API SCB Easy V3 endpoint = https://fasteasy.scbeasy.link 1.0. Get balance

SCB API Esay team 2 Sep 28, 2021
Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota & International

Courier API Courier API adalah project API untuk mengetahui ongkos kirim Logistik-logistik pengiriman barang antar kota (dalam negeri) & International

Rangga Darmajati 2 Sep 24, 2021
Laravel api tool kit is a set of tools that will help you to build a fast and well-organized API using laravel best practices.

Laravel API tool kit and best API practices Laravel api tool kit is a set of tools that will help you to build a fast and well-organized API using lar

Ahmed Esa 106 Nov 22, 2022
LaraBooks API - Simple API for iOS SwiftUI app tests.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Konrad Podrygalski 1 Nov 13, 2021
Best resources restful api for developers (with JSON:API standar specification design)

List API Best resources restful api for developers (with JSON:API standar specification design). API Resource Endpoint Name Resource Description Al Qu

Noval 2 Jan 18, 2022
GraphQL API to Studio Ghibli REST API

GhibliQL GhibliQL is a GraphQL wrapper to the Studio Ghibli REST API Usage First, you'll need a GraphQL client to query GhibliQL, like GraphQL IDE Con

Sebastien Bizet 8 Nov 5, 2022
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
API for Symbiota using the Lumen PHP PHP Micro-Framework By Laravel

symbiota-api API for Symbiota using the Lumen PHP PHP Micro-Framework By Laravel Laravel Lumen Official Documentation Documentation for the Lumen fram

Biodiversity Knowledge Integration Center 2 Jan 3, 2022