关闭CURL请求

时间:2012-05-04 06:54:34

标签: php curl

我正在尝试使用CURL请求从API检索一些数据。是否有可能跟踪从请求开始传递的时间并在某个时间后停止请求,可能会少于设置的超时时间?

注意:

我的目标是不设置超时。让请求继续,直到没有出现另一个作业/函数调用。有可能吗?

详细信息:

我真正想要的是,我有一个通过Ajax调用然后是CURL启动的函数,另一个Ajax也将使用某个特定参数调用该函数,当第二个ajax调用发生时,CURL的执行应该停止。但是这两次调用中的时间间隔是任意的。

5 个答案:

答案 0 :(得分:3)

您可以通过设置cURL转移的CURLOPT_CONNECTTIMEOUTCURLOPT_TIMEOUT选项(php doc)来定义

答案 1 :(得分:1)

使用可以使用 CURLOPT_CONNECTTIMEOUT CURLOPT_TIMEOUT 通过curl_setopt()功能设置cURL选项,如下所示:

<?php

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// The number of seconds to wait while trying to connect.
// Use 0 to wait indefinitely.
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

// The maximum number of seconds to allow cURL functions to execute
curl_setopt($ch, CURLOPT_TIMEOUT, 10)

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

答案 2 :(得分:1)

  

我真正想要的是,我有一个通过Ajax调用然后是CURL启动的函数,另一个Ajax也会调用具有某个特定参数的函数,当第二个ajax调用发生时,CURL的执行应该停止< / p>

然后您需要在JavaScript代码中执行此操作。在发送新的AJAX请求之前,只需.abort()

答案 3 :(得分:1)

我不确定你用什么来确定足够的时间,但以下内容会阻止卷曲下载:

curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($ch, "downloader"));

downloader只是一个随机函数名,它接受curl资源和函数名传递接收的输入以进行保存。它必须返回收到的长度,或连接中止,所以如果没有想要发生这种情况,你将拥有以下内容:

function downloader($curlHandle,$data)
         {
            $data_string .= $data; // Store your data for later.
            $data_length = strlen($data); // Get length of current chunk
            return $data_length;  // pass it back and keep going.
          }

现在,假设你有一个全局变量表示“停止卷曲!”您可以返回错误的大小并中止转移。类似的东西:

function downloader($curlHandle,$data)
         {
            $data_string .= $data; // Store your data for later.
            $data_length = strlen($data); // Get length of current chunk
            global $stop_curl;
            return ($stop_curl) ? "" : $data_length;
          }

答案 4 :(得分:-2)

以这种方式在PHP中获取脚本执行时间的简单方法:

function microtime_float()
{
    list($utime, $time) = explode(" ", microtime());
    return ((float)$utime + (float)$time);
}

$script_start = microtime_float();
// here your curl request start
....

// here your curl request stop
$script_end = microtime_float();

echo "Script executed in ".bcsub($script_end, $script_start, 4)." seconds.";
相关问题