I recently had the task of automatically “tweeting” when a new article was posted to one of the websites I had built, it turns out to be a pretty simple operation thanks to both Twitter and Bit.ly providing a straight forward API. An account with Bit.ly does have to be opened to obtain an API key.

I decided to use the built-in cURL functionality of PHP for interacting with the APIs. This code uses some of the JSON functions introduced in PHP 5.2.0 so a recent install of PHP is required as the Bit.ly API responds with a JSON string. On to the code…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function shorten_url($long_url) {
    $login = "username";
    $api   = "api key";
    if(!empty($long_url)) {
        $shortener = "http://api.bit.ly/shorten?version=2.0.1&longUrl={$long_url}&login={$login}&apiKey={$api}";
 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $shortener);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $x = curl_exec($ch);
        curl_close($ch);
 
        $json = json_decode($x,true);
        return ($json['statusCode'] == "OK") ? $json['results'][$long_url]['shortUrl'] : false;
    } else {
        return false;
    }
}
 
function twitter($status,$url) {
    $username = "username";
    $password = "password";
    if(!empty($status)) {
        $limit = 140;
        if($short = shorten_url($url)) {
            $length = ($limit - (strlen($short) + 4));
            $status = (strlen($status) > $length) ? substr($status,0,$length)."... ".$short : $status." ".$short;
 
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/update.xml");
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_USERPWD, "{$username}:{$password}");
            curl_setopt($ch, CURLOPT_POSTFIELDS, "status=".$status);
            $x = curl_exec($ch);
            curl_close($ch);
 
            $p = xml_parser_create();
            xml_parse_into_struct($p, $x, $vals, $index);
            xml_parser_free($p);
            return ($vals[0]['tag'] == "STATUS") ? true : false;
        } else {
            return false;
        }
    } else {
        return false;
    }
}