Skip to Content

Using PHP and Curl to post to Twitter

Twitter has become a very successful social media site which is based around the concept of people providing status updates to others using very short messages (less than 140 characters).

Twitter has a very good API which allows coders to send messages from their own sites in order to update their status. The following PHP code can be used to update a twitter account using Twitter's API. To use this code, first sign up for a twitter account and then change the username and password of the code below to reflect your own login details.

// set username and password
$username = 'twitter_username';
$password = 'twitter_password';
// add the message you want to send
$message = 'is tweeting using php and curl';
// set the twitter API address
$url = 'http://twitter.com/statuses/update.json';
// setup a curl process
$curl_handle = curl_init();
// set the url of the curl process
curl_setopt($curl_handle, CURLOPT_URL, "$url");
// saves the return value as a string value instead of outputting to browser
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
// to send data as $_POST fields as required by the twitter API
curl_setopt($curl_handle, CURLOPT_POST, 1);
// set the post fields
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
// set the username and password for the connection
curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
// exectute the curl request and save output as $buffer variable
$buffer = curl_exec($curl_handle);
// close the curl connection
curl_close($curl_handle);
// decode json output into array
$json_output = json_decode($buffer, true);
// check for success or failure
if (isset($json_output['error'])) {
    // tweet not successful, display error
    echo "Fail: ".$json_output['error'];
}
else {
    // tweet is successful
    //$json_output contains return variables for this tweet
    echo "Success";
}

Note that this code uses the JSON update url so that the output is returned in JSON format. The contents of successful tweet updates can then be accessed through the $json_output variable as a normal array.

DId you like this?

If you liked this, why not make a donation and help support ongoing development.