A simple function using Curl to post (GET) to Twitter


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. | <?php
  2.  
  3. // A simple function using Curl to post (GET) to Twitter
  4. // Kosso : March 14 2007
  5.  
  6. // Feel free to do what you like with this.
  7. // It's pretty easy. But I thought I'd just put it out there.
  8. // Curl is your friend.
  9.  
  10. // usage : postToTwitter("myusername","mypassword","hello twitterati! I'm posting this from a PHP script! woo!");
  11.  
  12. /////////////////////////////////////////////////////////////////////
  13.  
  14.  
  15. function postToTwitter($username,$password,$message){
  16.  
  17. // GET the API url via web authentication
  18. // add 'status' param to send a message to Twitter
  19.  
  20. $host = "http://twitter.com/statuses/update.xml?status=".urlencode(stripslashes(urldecode($message)));
  21.  
  22. $ch = curl_init();
  23. curl_setopt($ch, CURLOPT_URL, $host);
  24. curl_setopt($ch, CURLOPT_VERBOSE, 1);
  25. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  26. curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
  27. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  28. curl_setopt($ch, CURLOPT_POST, 1);
  29.  
  30. // Go for it!!!
  31. $result = curl_exec($ch);
  32. // Look at the returned header
  33. $resultArray = curl_getinfo($ch);
  34.  
  35. // close curl
  36. curl_close($ch);
  37.  
  38. //echo "http code: ".$resultArray['http_code']."<br />";
  39.  
  40. if($resultArray['http_code'] == "200"){
  41. echo "<br />OK! posted to http://twitter.com/".$username."/<br />";
  42. } else {
  43. echo "eek! yegads! error posting to Twitter";
  44. }
  45.  
  46. // debug the result
  47. // echo "<pre>";
  48. // print_r($resultArray);
  49. // echo "</pre><hr>";
  50.  
  51. // $sResult = htmlentities($result);
  52. // $sResult = str_replace("&gt;&lt;","&gt;<br />&lt;",$sResult);
  53.  
  54. // echo "<pre>";
  55. // print $sResult;
  56. // echo "</pre>";
  57.  
  58. }
  59.  
  60. // ok, you can stop reading now
  61.  
  62. // no, seriously. ;p
  63.  
  64. ?> |

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.