0

I use curl to make a call to the API like this:


$curl = curl_init();

if (isset($_COOKIE['session'])) {
    curl_setopt($curl, CURLOPT_COOKIE, 'session=' . $_COOKIE['session']);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_URL, $query_url);
    $result = curl_exec($curl);
}
else {
    $result = 'Cookie is expired';
}
curl_close($curl);

print $result;

Then I run this PHP file to test it and during testing when I load the file I receive nothing, when I restart the page I get the data that I need. When I use it with javascript behavior is similar.

When I test it with Postman, it works just fine.

Why doesn't it wait for a response and returns it to me then, but rather sends me the empty page first time around and only after page reload it returns a proper response?

Edit: JSON return is quite huge so it usually take a server around 1.5-2 seconds to return it

Ademir Gotov
  • 179
  • 1
  • 14
  • You might check the HTTP status code of the first call, possibly with [curl_getinfo](https://www.php.net/manual/en/function.curl-getinfo.php#example-5404). – showdev Jul 03 '19 at 15:58
  • @showdev keep getting 0 on the first request and then 200 on the second, thanks for the hint – Ademir Gotov Jul 03 '19 at 16:04
  • 1
    Sounds like an issue with the API, not your code. – Barmar Jul 03 '19 at 16:06
  • Hm, then maybe check [`curl_error`](https://www.php.net/manual/en/function.curl-error.php). – showdev Jul 03 '19 at 16:07
  • @showdev it returns 7. A workaround I found is using: `$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($http_code == 0) { $result = curl_exec($curl); }`, but I think it is a bad approach – Ademir Gotov Jul 03 '19 at 16:09
  • 1
    An error code of "7" indicates: "Failed to connect() to host or proxy". See [How to resolve cURL Error (7): couldn't connect to host?](https://stackoverflow.com/a/9923212/924299). – showdev Jul 03 '19 at 16:12

1 Answers1

0

Seems like it is an issue with the server I am trying to connect to and there is not much I can do except for this workaround:

if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 0) { $result = curl_exec($curl); }

Here is the final snippet:

$curl = curl_init();

if (isset($_COOKIE['session'])) {
    curl_setopt($curl, CURLOPT_COOKIE, 'session=' . $_COOKIE['session']);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_URL, $query_url);
    $result = curl_exec($curl);
    if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 0) {
        $result = curl_exec($curl);
    }
}
else {
    $result = 'Cookie is expired';
}
curl_close($curl);

print $result;
Ademir Gotov
  • 179
  • 1
  • 14