0

To get some API data, I am using following cURL code in PHP:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "some_api_url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
if(curl_errno($ch))
{
    echo "cURL error: " . curl_error($ch);
}
curl_close($ch);
echo $response;

Now, the question is that what is the point of having CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT in my code?

The code does pretty well even without these two settings.

Then why do docs and people on Internet advise using this particular settings?

UPDATE

I am not asking the difference between these two curl setting options. Rather than I asked about the need to include them in my code. The suggested post link (due to this, my question is almost marked as duplicate) does not address to my question. Also people there have so much different opinions and misjudge each other in various comments.

Sachin
  • 1,646
  • 3
  • 22
  • 59
  • Does this answer your question? [PHP cURL: CURLOPT\_CONNECTTIMEOUT vs CURLOPT\_TIMEOUT](https://stackoverflow.com/questions/27776129/php-curl-curlopt-connecttimeout-vs-curlopt-timeout) – JMP Mar 04 '23 at 10:26
  • No, not at all. I explained in `UPDATE`. Btw, @shingo has explained me what I was looking for. – Sachin Mar 04 '23 at 12:50

1 Answers1

1

If you do not have these two options, and it happens that the URL you visit fails to respond to your request, the function curl_exec will never return. If this php script is used as a page on your website, when your customers visit it, they will see a blank page until the browser shows that the connection has timed out. So it's a good practice to always set the timeout options, this will give you a chance to display a customized error UI.

As an example, you can create a simple php like this, and use the above cURL code to visit it, I think you can find the difference.

<?php
sleep(999);
shingo
  • 18,436
  • 5
  • 23
  • 42
  • Yes, by delaying my server script for some seconds greater than `CURLOPT_TIMEOUT`, I found the difference. Thanks! – Sachin Mar 04 '23 at 12:48