PHP update Twitter

In: PHP

July 02nd, 2010.

To use PHP update Twitter status, all you need is following function. Call this function from your PHP application sending your Twitter username, Twitter password, status, and link to a source you want to link.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function publish_on_twitter($username, $password, $title, $url) {
	$twitter_url = 'http://twitter.com/statuses/update.xml';
 
	$tiny_url =  file_get_contents('http://tinyurl.com/api-create.php?url=' . $url);
	$status = $title . ' ' . $url;
	if(strlen($status) > 160) $status = $title . ' ' . $tiny_url;
 
	$curl_handle = curl_init();
	curl_setopt($curl_handle, CURLOPT_URL, "$twitter_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=$status");
	curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
 
	$buffer = curl_exec($curl_handle);
	curl_close($curl_handle);
 
	if (empty($buffer)) return 'Twitter update fail.';
	return 'Twitter update success!';
}

Written by

Dejan is pragmatic software developer with Master's Degree in Computer Science. He is currently based in Belgrade (Serbia).