How to get instagram photos with PHP by API?

How to get instagram photos with PHP by API?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Your Instagram PHP Integration Fails and How to Fix It

Encountering Notice: Trying to get property of non-object and Warning: Invalid argument supplied for foreach() when pulling data from the Instagram API is a classic symptom of how the v1 API structures its JSON response. The error occurs specifically at line 29 in your code, where you attempt to iterate over $result->data.

The root cause isn't necessarily an invalid access token, though that is a possibility. It is more likely that json_decode returned null or an object without a data property because the request failed silently before execution reached the loop. When you use cURL with CURLOPT_RETURNTRANSFER, $result holds the raw HTTP response string. If the server returns a 401 Unauthorized, 403 Forbidden, or even a malformed JSON error message, your current code decodes that failure string into an object (or null) and then tries to access properties that don't exist.

Decoding the Response Safely

To resolve this, you must validate the structure of the decoded JSON before attempting to iterate. The Instagram v1 API often wraps errors in a specific format where the data key might be absent, or the top-level object itself indicates failure.

Update your fetching logic to check the HTTP status code and validate the decoded object:

$result = fetchData("https://api.instagram.com/v1/users/3550421370/media/recent/?access_token=YOUR_ACCESS_TOKEN");

if ($result === false) {
    // curl_exec failed (network error, timeout, etc.)
    die('cURL request failed.');
}

$data = json_decode($result);

// Check if decoding was successful and if the 'data' property exists
if ($data === null || !isset($data->data) || !is_array($data->data)) {
    // The API returned an error or no media was found
    // $data->error might contain details about why (e.g., expired token, missing permissions)
    if (isset($data->error)) {
        echo "API Error: " . json_encode($data->error);
    } else {
        echo "No data property found in response.";
    }
    exit;
}

foreach ($data->data as $post) {
    // Proceed only if caption exists
    if (!empty($post->caption->text)) {
        echo '<a class="instagram-unit" target="_blank" href="' . htmlspecialchars($post->link) . '">';
        echo '<img src="' . htmlspecialchars($post->images->low_resolution->url) . '" alt="' . htmlspecialchars($post->caption->text) . '" width="100%" height="auto" />';
        echo '<div class="instagram-desc">' . htmlspecialchars($post->caption->text) . ' | ' . date("F j, Y, g:i a", strtotime($post->caption->created_time)) . '</div></a>';
    }
}

The Critical Role of Scopes and Permissions

A common reason for "non-object" responses even with valid credentials is insufficient scope. Your source material mentions creating authentication from the Instagram API, but simply obtaining a user ID and an access token is not enough to fetch media.

The Instagram v1 API distinguishes between account-level data (like profile info) and user-level data (like posts). To read the recent media of a specific user, your OAuth access token must include the instagram_read scope. If you generated a token using only basic permissions or if the token was issued for a different application with restricted scopes, the API will reject the request, often returning an empty object structure that triggers the "property of non-object" error.

Additionally, ensure your clientId and userId are correctly associated with the token. If you are accessing your own profile, the token should be generated specifically for that account.

Why JavaScript Plugins Often Seem to Work Better

You noted that switching to a JavaScript plugin like instafeedjs resolved the issue immediately. This happens because many client-side libraries handle error parsing and HTTP status codes differently than raw PHP scripts. They might catch the 401 or malformed JSON response, log it to the browser console, and simply render nothing if an error occurs, rather than crashing your page with a PHP warning. However, relying on third-party plugins introduces dependency risks and limits customization compared to building a native API integration.

The Path Forward: Migrating to v2

While fixing the immediate error is important, it is worth noting that the Instagram Graph API v1 (the endpoint you are currently using) is deprecated. For new projects or long-term stability, you should migrate to the Instagram Basic Display API or the Graph API v2. The newer endpoints use OAuth 2.0 flow, which provides better security and clearer error messages than the legacy access_token appended directly to the URL.

If you are building a Laravel application, consider using packages like mellikam/instagram-api-laravel. These tools abstract the complex OAuth flows and handle token refreshing automatically, preventing issues where an expired access token causes your entire feed to stop loading without clear feedback.

By validating your response structure rigorously and ensuring your OAuth scopes match the required permissions for media retrieval, you can eliminate the "non-object" errors and build a robust Instagram feed integration.

Our network