Skip to content
PHP Logo

What are some best practices for securely retrieving Twitter follower count using PHP?

When retrieving Twitter follower count using PHP, it's important to securely authenticate the request to ensure the data is being accessed securely. One way to do this is by using OAuth authentication to authenticate the API request. This ensures that only authorized users can access the follower count data.

php
<?php

$consumerKey = 'YOUR_CONSUMER_KEY';
$consumerSecret = 'YOUR_CONSUMER_SECRET';
$accessToken = 'YOUR_ACCESS_TOKEN';
$accessTokenSecret = 'YOUR_ACCESS_TOKEN_SECRET';

$twitterUsername = 'USERNAME';

$oauthAccessToken = $accessToken;
$oauthAccessTokenSecret = $accessTokenSecret;
$oauthConsumerKey = $consumerKey;
$oauthConsumerSecret = $consumerSecret;

$connection = curl_init();
curl_setopt_array($connection, array(
    CURLOPT_URL => "https://api.twitter.com/1.1/users/show.json?screen_name=$twitterUsername",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => false,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_HTTPHEADER => array(
        'Authorization: OAuth oauth_consumer_key="' . $oauthConsumerKey . '", oauth_nonce="' . time() . '", oauth_signature="' . $oauthConsumerSecret . '&", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' . time() . '", oauth_token="' . $oauthAccessToken . '", oauth_version="1.0"'
    )
));

$data = curl_exec($connection);
curl_close($connection);

$userData = json_decode($data, true);
$followerCount = $userData['followers_count'];

echo "Follower Count: " . $followerCount;

?>