Skip to content

Instantly share code, notes, and snippets.

@cellfish
Last active December 31, 2015 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cellfish/8011266 to your computer and use it in GitHub Desktop.
Save cellfish/8011266 to your computer and use it in GitHub Desktop.
How to post tweets from PHP.
function postTweet($text)
{
$tweet = utf8_encode($text);
$data_array = array('status' => $tweet);
$postfields = http_build_query($data_array);
$url = "https://api.twitter.com/1.1/statuses/update.json";
$oauth_access_token = "PUT YOUR TOKEN HERE";
$oauth_access_token_secret = "PUT YOUR TOKEN SECRET HERE";
$consumer_key = "PUT YOUR CONSUMER KEY HERE";
$consumer_secret = "PUT YOUR CONSUMER SECRET HERE";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => rand() . rand(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0',
'status' => $tweet);
$base_info = buildBaseString($url, 'POST', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth));
// Make Requests
$options = array( CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => $header,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return $json;
}
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
{
if (substr($key, 0, 5) == "oauth")
$values[] = "$key=\"" . rawurlencode($value) . "\"";
}
$r .= implode(', ', $values);
return $r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment