简体   繁体   中英

How to Tweet in Twitter using PHP

How can I tweet in twitter from my website? I am using a PHP script. Whatever tweets I send from my website should update my twitter account. I use the following code, but it is not updating in my twitter account:

// Set username and password
$username='myusername';
$password='*********';
// The message you want to send
$message = 'Nice to c all again.Have a nice day..';
// The twitter API address
$url='http://twitter.com/statuses/update.xml';
// Alternative JSON version
// $url = 'http://twitter.com/statuses/update.json';
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST,1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS,"status=".$message);
curl_setopt($curl_handle, CURLOPT_USERPWD,"$username:$password");
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
// check for success or failure
if (empty($buffer)) {
    echo 'Try again';
} else {
    echo 'success';
}

This script is returning a success message, but when I check my twitter account no tweets are found.

What could be the problem?

You are trying to send tweets using Basic Authentication (user name and password). This is no longer allowed. There are many examples of this online, but Twitter turned it off last August. You now have to use OAuth to do authentication.

to tweet using twitter you will need a post_authenticity_token along with your username and password . this token can be obtained from your profile page by fetching it using curl (after you login with curl). i experimented with curl and was able to tweet using curl. you can find my code at (though it is in bash script, it can be ported to php easily coz they both use curl ) http://pastebin.com/a5eBcEeP .

You can find a list of PHP libraries that support OAUTH and you can use to write a tweet function in PHP and the 1.1 version of the Twitter API here: https://dev.twitter.com/docs/twitter-libraries

tmhOAuth is probably my favorite.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM