Search code examples
phphttphttp-headerstwitter

Retrieve Twitter's X-RateLimit-Limit in PHP


With every Twitter request I make, the returned HTTP headers should include X-RateLimit-Limit.

However, I seem unable to retrieve these using PHP. Can someone tell me what bone-headed mistake I've made?

I've set my curl up in the normal way and am able to successfully GET and POST requests.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);

$response = curl_exec($ch);
$response_info=curl_getinfo($ch);
$erno = curl_errno($ch);
$er = curl_error($ch);
curl_close($ch);

I'm able to get some response information, like http_code

$response_info['http_code']

But this line just returns null

//Doesn't bloody work. No idea why!
$rate_limit = $response_info['X-RateLimit-Limit'];

I'm running PHP Version 5.3.10.

EDIT

This is the result of print_r($response_info);

Array
(
[url] => https://api.twitter.com/1/statuses/home_timeline.json...
[content_type] => application/json;charset=utf-8
[http_code] => 200
[header_size] => 695
[request_size] => 410
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 1.239977
[namelookup_time] => 0.007361
[connect_time] => 0.155783
[pretransfer_time] => 0.465397
[size_upload] => 0
[size_download] => 99425
[speed_download] => 80182
[speed_upload] => 0
[download_content_length] => 99425
[upload_content_length] => 0
[starttransfer_time] => 0.794829
[redirect_time] => 0
[certinfo] => Array()
[redirect_url] => 
[request_header] => GET /1/statuses/home_timeline.json... HTTP/1.1
Host: api.twitter.com
Accept: */*
)

Solution

  • curl_getinfo does not return the response headers, only other meta info about the request. To retrieve headers, set CURLOPT_HEADER to true. That will include the headers in the output. To separate them from the response body do:

    list($headers, $body) = explode("\n\n", $response, 2);
    

    To parse the headers, explode again:

    $headers = explode("\n", $headers);
    foreach ($headers as $header) {
        list($key, $value) = explode(':', $header, 2);
        $headers[trim($key)] = trim($value);
    }
    
    echo $headers['X-RateLimit-Limit'];