PHP API Request Times Out Even Though Endpoint Works

1
php


<?php if (is_user_logged_in());

?>

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?

Adding CSS and HTML to test:

css

.testt {
}
html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My First Webpage</title>
</head>
<body>
  <h1>Welcome to My Webpage</h1>
  <p>Your FAce Is COde!.</p>
</body>
</html>
Loading discussion…Preparing formatted code and rich content.
Your Answer

Respond directly to the original question. To respond to another answer, use Reply under that answer.

Have an answer?

Log in with your ProfoundSyntax account to participate.

Log In to Reply

2 Answers

Thread contextShowing the selected reply branch and its parent context.View full discussion
  1. 0
    Da Code Master
    Da Code Master V MOD PRO
    @derekwcodes 0 rep edited
    Replying to @diamondj

    The fact that some requests finish in under a second while others hit the 30-second timeout suggests an intermittent connection or response issue, but I wouldn't rule out PHP or the hosting environment without checking the timing data first.

    **cURL error 28 doesn't necessarily mean the API is down.** It means the operation exceeded its configured timeout. Even if the API works when tested directly, the PHP server could be experiencing DNS delays, connection problems, TLS negotiation issues, or delays waiting for a response.

    I'd start by adding detailed cURL timing diagnostics immediately after curl_exec():

    php

    $response = curl_exec($ch);
    
    $info = curl_getinfo($ch);
    
    $diagnostics = [
        'dns_time' => $info['namelookup_time'],
        'connect_time' => $info['connect_time'],
        'tls_time' => $info['appconnect_time'] ?? null,
        'first_byte_time' => $info['starttransfer_time'],
        'total_time' => $info['total_time'],
        'http_code' => $info['http_code'],
        'primary_ip' => $info['primary_ip'] ?? null,
        'curl_errno' => curl_errno($ch),
        'curl_error' => curl_error($ch)
    ];
    
    error_log(json_encode($diagnostics));

    The important part is comparing successful requests against failed ones.

    – If DNS lookup times are unusually high, investigate DNS resolution.
    – If connection establishment is slow, check outbound firewall rules, routing, IPv4/IPv6 connectivity, and hosting network restrictions.
    – If the connection completes quickly but the first response byte is delayed, investigate API-side processing, rate limits, or upstream services.
    – If the timing looks normal until a particular point, compare the affected requests and any redirects.

    I'd also test the same endpoint directly **from the server running PHP**, rather than relying solely on a browser or another computer. That can help identify differences between the two environments.

    **Regarding retries:** Yes, retries are useful for transient failures, but they should be controlled.

    For safe, read-only requests, I'd generally start with a maximum of two retries, exponential backoff, and a little random jitter. Respect the API's Retry-After header when applicable.

    Be careful with POST or other requests that modify data. A timeout doesn't guarantee the remote API failed to process the original request. Retrying could create duplicates unless the API supports idempotency keys or another deduplication mechanism.

    I also wouldn't increase CURLOPT_TIMEOUT beyond 30 seconds until the actual bottleneck is identified. A longer timeout can simply make failures take longer.

    My recommendation: Start by capturing cURL timing data for both successful and failed requests. That should narrow down whether you're dealing with DNS, connection establishment, or a remote response delay.

    One question: When the timeout happens, does it affect requests to other external APIs from the same PHP server, or only this particular endpoint? That would be useful information for isolating the problem.

    The diagnostic approach is supported by the official PHP cURL documentation: https://www.php.net/manual/en/function.curl-getinfo.php and the official cURL retry guidance: https://everything.curl.dev/usingcurl/downloads/retry.html

    Insightful 1