Twitter 401 Unauthorized — OAuth Request Token


#1

I am using file_get_contents in PHP to make HTTP requests to the Twitter API. When trying to request a token, I get the error:

Warning: file_get_contents(https://api.twitter.com/oauth/request_token): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized

Here is my code

$appID = "MY-CONSUMER-ID";
$appSecret = "MY-CONSUMER-SECRET";

$url = "https://api.twitter.com/oauth/request_token";

$oauth = array(
    "oauth_nonce" => base64_encode(time()),        
    "oauth_callback" => "MY-URL",
    "oauth_signature_method" => "HMAC-SHA1",
    "oauth_timestamp" => time(),
    "oauth_consumer_key" => $appID,
    "oauth_version" => "1.0"
);

$token_string = "POST&" . rawurlencode($url) . "&" . rawurlencode(http_build_query($oauth));
$signing_key = rawurlencode($appSecret) . "&";
$signature = base64_encode(hash_hmac("sha1", $token_string, $signing_key, true));

$oauth["oauth_signature"] = $signature;

$header = array();
foreach ($oauth as $key => $value) { $header[] = rawurlencode($key) . "=\"" . rawurlencode($value) . "\""; }
$header = implode(", ", $header);
$header = "Authorization: OAuth " . $header;

$opts = array('http' => array(
    'method'  => "POST",
    'header'  => $header,
) );

$context  = stream_context_create($opts);
$result = file_get_contents($url, false, $context);