Skip to content

PHP API Request Times Out Even Though Endpoint Works

0

I am trying to make a PHP request to an external API, but the request periodically times out even though the API endpoint itself appears to be online and responding normally when I test it directly.

The problem does not happen on every request. Some requests complete in less than a second, while others wait until the timeout limit is reached.

I am trying to determine whether this is more likely to be caused by my PHP configuration, the remote API, DNS/network latency, or the way I am handling the request.

Current PHP code

php
<?php

$url = 'https://api.example.com/products';

$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTPHEADER => <span class="text-token-text-primary cursor-text rounded-sm" data-placeholder-token="true">[
        'Accept: application/json',
    ]</span>,
]);

$response = curl_exec($ch);

if ($response === false) {
    echo 'cURL Error: ' . curl_error($ch);
} else {
    $data = json_decode($response, true);

    echo '<pre>';
    print_r($data);
    echo '</pre>';
}

curl_close($ch);

What I have already checked

  1. The API URL loads successfully when tested directly.
  2. PHP cURL is enabled on the server.
  3. Most requests work correctly.
  4. Increasing CURLOPT_TIMEOUT only makes failed requests take longer before returning an error.
  5. The server itself does not appear to be under unusually high CPU or memory usage.
  6. The issue happens intermittently rather than on every request.

Example error

code
cURL error 28:
Operation timed out after 30001 milliseconds
with 0 bytes received

What I am trying to figure out

What would be the best way to troubleshoot this?

Would you recommend checking:

  • DNS lookup time?
  • connection time separately from total request time?
  • remote server response headers?
  • PHP-FPM limits?
  • firewall or outbound connection rules?
  • retry logic?
  • API rate limiting?
  • logging detailed cURL timing information?

I would also like to know whether automatically retrying the request is considered a good approach, or whether that could make the problem worse if the remote API is already having trouble.

If retries are appropriate, what would be a reasonable retry strategy in PHP without causing duplicate requests or unnecessary load?

Unanswered No answer has been accepted yet.

0 Answers

Have an answer?

Log in with your ProfoundSyntax account to participate.

Log In to Reply