title: Twitter 401 Unauthorized -- OAuth Request Token
body: <p>I am using <code>file_get_contents</code> in PHP to make HTTP requests to the Twitter API.
  When trying to request a token, I get the error:</p>
  
  <pre><code>Warning: file_get_contents(https://api.twitter.com/oauth/request_token): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
  </code></pre>
  
  <p>Here is my code</p>
  
  <pre><code>$appID = "MY-CONSUMER-ID";
  $appSecret = "MY-CONSUMER-SECRET";
  
  $url = "https://api.twitter.com/oauth/request_token";
  
  $oauth = array(
      "oauth_nonce" =&gt; base64_encode(time()),        
      "oauth_callback" =&gt; "MY-URL",
      "oauth_signature_method" =&gt; "HMAC-SHA1",
      "oauth_timestamp" =&gt; time(),
      "oauth_consumer_key" =&gt; $appID,
      "oauth_version" =&gt; "1.0"
  );
  
  $token_string = "POST&amp;" . rawurlencode($url) . "&amp;" . rawurlencode(http_build_query($oauth));
  $signing_key = rawurlencode($appSecret) . "&amp;";
  $signature = base64_encode(hash_hmac("sha1", $token_string, $signing_key, true));
  
  $oauth["oauth_signature"] = $signature;
  
  $header = array();
  foreach ($oauth as $key =&gt; $value) { $header[] = rawurlencode($key) . "=\"" . rawurlencode($value) . "\""; }
  $header = implode(", ", $header);
  $header = "Authorization: OAuth " . $header;
  echo $header;
  
  $opts = array('http' =&gt; array(
      'method'  =&gt; "POST",
      'header'  =&gt; $header,
  ) );
  
  $context  = stream_context_create($opts);
  $result = file_get_contents($url, false, $context);
  </code></pre>