0

I use this function (from here) with cURL in PHP:

<?php
function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

This works quite well - - for example, that way I can get the 'body' of a JSON. Like this:

<?php
$crossrefurl = 'https://api.crossref.org/works/10.1163/1871191X-13020004';
$obj = file_get_contents_curl($crossrefurl);

# convert to json
$obj = json_decode($obj, true);

What I don't know is: how can I get the response status code (given that my ´curl`-commands are in a function)?

Specifically, I want to find out whether the response status code is 429 in which case I would let the script sleep for 5 seconds (to avoid being rate-limited).

According to this post, the code should be something like:

<?php
if(($httpcode == 429)) { sleep(5); }

... but how do I get to $httpcode in the first place?

Thanks for your help!

anpami
  • 760
  • 5
  • 17
  • Could use https://www.php.net/manual/en/function.get-headers.php to get status code... or `curl_getinfo($ch, CURLINFO_HTTP_CODE)`https://www.php.net/manual/en/function.curl-getinfo.php – user3783243 Oct 14 '22 at 19:50
  • @user3783243, thank you! But where exactly should this be placed? Not really in the function, right? How would I store that information into `$httpcode`? – anpami Oct 14 '22 at 20:00
  • You could return an array, put status code as index 0 and `$data` as next index. You need CURL connection open to use this. – user3783243 Oct 14 '22 at 20:08

0 Answers0