php - 如果服务器在 2 秒后没有响应,如何使 cURL 返回 false?

标签 php curl

我得到了这个功能,现在有时当网站关闭或长时间加载时,它会减慢我网站的加载时间。

如果服务器在 2 秒内没有响应,有什么方法可以让它只返回 false 吗?如您所见,我使用 CURLOPT_CONNECTTIMEOUT 进行了尝试,但似乎没有成功。

function url_get_contents($url)
{
    if (!function_exists('curl_init'))
    {
        die('Exit: CURL is not installed or enabled!');
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
    $output = curl_exec($ch);
    curl_close($ch);

    return $output;
}

最佳答案

简答:

curl_setopt($ch, CURLOPT_TIMEOUT, 2);


引用自 PHP cURL documentation :

CURLOPT_CONNECTTIMEOUT: The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.

CURLOPT_TIMEOUT The maximum number of seconds to allow cURL functions to execute.

关于php - 如果服务器在 2 秒后没有响应,如何使 cURL 返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18935997/

相关文章:

php - CURL:发布表单并从 bash 获取数据

java - 如何增加curl GET请求url大小限制?

javascript - 获取group_name的文本元素

php - 返回给定整数的下一个最接近的 2 次幂

php - 什么时候不关闭 php 文件?

php - Codeigniter 3x 查询生成器类似乎正在为我的查询生成额外的段

curl - 使用 REST API 更新 JIRA 票证状态

docker - CURL在Docker镜像中不起作用[无法访问Docker镜像中的主机]

java - 无法再从 oracle 站点 curl JDK

javascript - Laravel:尝试在 View 模板中访问数组内的值