How to retrieve Twitter profile picture using API v1.1

I’m completely stuck trying to fetch a user’s profile picture from Twitter. I’ve been reading through the documentation but I can’t figure out the right approach.

Here’s what I have so far but it’s not working:

if(isset($_POST['username'])){
    $username = htmlspecialchars($_POST['username']);
}

$cacheFile = 'temp/avatar_cache.json';
if(time() - filemtime($cacheFile) > 120){
    include 'libs/twitter_api.php';
    $api = new TwitterAPI('consumer_key','consumer_secret', 'access_token', 'token_secret');
    $result = $api->get('users/show', array('screen_name' => $username));
    file_put_contents($cacheFile, json_encode($result));
}else{
    echo 'Using cached data';
    $result = json_decode(file_get_contents($cacheFile), true);
}

Can someone point me in the right direction? I just need to get the avatar image for any given Twitter username. Thanks in advance for any help!

The Problem:

You are trying to fetch a user’s profile picture from Twitter using their API, but your code isn’t correctly extracting the image URL from the API response. Your current code successfully makes the API call and caches the results, but it doesn’t display the avatar image.

TL;DR: The Quick Fix:

Add these lines after your $result = json_decode(...) line to extract and display the avatar URL:

$avatar_url = $result['profile_image_url'];
echo '<img src="' . $avatar_url . '" alt="Profile Picture">';

Step-by-Step Guide:

  1. Extract the Profile Image URL: After you successfully retrieve the JSON response from the Twitter API, extract the profile_image_url property. This property contains the URL of the user’s profile picture. Modify your code as follows:
if(isset($_POST['username'])){
    $username = htmlspecialchars($_POST['username']);
}

$cacheFile = 'temp/avatar_cache.json';
if(!file_exists($cacheFile) || time() - filemtime($cacheFile) > 120){
    include 'libs/twitter_api.php';
    $api = new TwitterAPI('consumer_key','consumer_secret', 'access_token', 'token_secret');
    $result = $api->get('users/show', array('screen_name' => $username));
    file_put_contents($cacheFile, json_encode($result));
}else{
    echo 'Using cached data';
    $result = json_decode(file_get_contents($cacheFile), true);
}

// **ADD THIS SECTION**
if (isset($result['profile_image_url'])) {
    $avatar_url = $result['profile_image_url'];
    //Optional:  Enhance image quality.  Twitter provides different sizes.
    $avatar_url = str_replace('_normal', '_400x400', $avatar_url); //Example:  Get a larger 400x400 image.

    echo '<img src="' . $avatar_url . '" alt="Profile Picture">';
} else {
    echo "Profile image URL not found for user: " . $username;
}

  1. Handle Errors: The Twitter API might return an error if the username doesn’t exist or if you hit rate limits. Wrap your $result['profile_image_url'] extraction in a conditional statement to check if the profile_image_url key exists in the $result array before trying to access it. If it does not exist, handle the error gracefully (e.g., display a message). The example above shows how to handle the case where the key isn’t found.

  2. Ensure temp Directory Exists: Verify that the temp directory exists before attempting to use it for caching. Create it if it doesn’t exist:

$cacheDir = 'temp';
if (!is_dir($cacheDir)) {
    mkdir($cacheDir, 0777, true); // Create the directory with appropriate permissions.
}
  1. Handle HTTPS: While less common now, the profile_image_url may sometimes return an HTTP URL even if the site is HTTPS. Use str_replace to force HTTPS to avoid mixed content warnings in the browser:
$avatar_url = str_replace('http://', 'https://', $avatar_url);

Common Pitfalls & What to Check Next:

  • API Key and Authentication: Double-check that your Twitter API keys (consumer_key, consumer_secret, access_token, token_secret) are correctly configured in your libs/twitter_api.php file.

  • Rate Limits: Twitter enforces rate limits on API requests. Implement proper error handling and potentially add delays between requests to avoid exceeding these limits.

  • JSON Decoding Errors: Ensure your json_decode function is working correctly and handling potential errors. Check the $result variable for any unexpected values after the json_decode. If the decoding fails, you won’t be able to access the profile_image_url property.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

The main issue is you’re fetching the data but never actually displaying the image URL. Once you get your result object, extract the profile picture like this:

$profile_pic = $result['profile_image_url'];
echo $profile_pic;

Nobody mentioned this - your cache file path might break if the temp directory doesn’t exist. Create it first or use a relative path you know exists.

Twitter’s profile_image_url field sometimes returns HTTP URLs even for HTTPS sites, causing mixed content warnings. Force HTTPS with a quick str_replace on the URL protocol.

The API response structure changes depending on whether the user exists, so wrap your extraction in proper error checking to avoid undefined index notices.

Your code looks mostly right, but you’re not actually pulling the profile picture URL from the API response.

Once you get the result back, grab the profile_image_url field:

if(isset($result->profile_image_url)){
    $avatar_url = $result->profile_image_url;
    // Replace _normal with _bigger for higher quality
    $avatar_url = str_replace('_normal', '_400x400', $avatar_url);
    echo $avatar_url;
}

The API gives you different image sizes. Just swap out the suffix in the URL to get bigger versions.

Honestly, Twitter API auth and rate limits are a huge pain. I’ve been doing social media automation for years and found that visual platforms save me tons of headaches.

Skip all this PHP code and credential management - build the whole thing in minutes. Create a workflow that takes a username, hits the Twitter API, grabs the profile image URL, and spits it back out. Zero code required.

Throw in error handling, caching, and image processing automatically. It handles all the auth nonsense too.

Check it out: https://latenode.com

u missed the extraction part. after getting the json response, just grab the profile_image_url prop like this: $avatar = $result['profile_image_url']; then echo it. also, double check ur json_decode too - that can trip u up sometimes.

You’re getting the data but not showing the profile image URL. After your API call works, grab the profile_image_url from the response:

if(isset($result->profile_image_url)){
    $profileImage = $result->profile_image_url;
    echo $profileImage;
}

Always check your API response first - learned this the hard way. Twitter throws weird errors and your code breaks if the username doesn’t exist or you hit rate limits.

Watch out for corrupted cache files or bad JSON too. I’ve seen this kill production apps. Add some validation around json_decode so you don’t get burned.

You’re setting up the API call but not actually extracting the image URL from the response.

After getting your result, dig into the JSON:

$avatar_url = $result['profile_image_url'];
echo '<img src="' . $avatar_url . '" alt="Profile Picture">';

Twitter serves tiny images by default - you’ll get a crappy 48x48 version that looks awful on modern screens.

Replace the size suffix for better quality:

$avatar_url = str_replace('_normal.jpg', '_200x200.jpg', $result['profile_image_url']);

Your cache logic has a bug. What happens when the file doesn’t exist yet? filemtime() throws a warning.

Add file_exists() first:

if(!file_exists($cacheFile) || time() - filemtime($cacheFile) > 120){
    // API call
}

Twitter rate limits are brutal so caching is definitely smart. Just beef up your error handling - user lookups fail way more than you’d think.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.