cURL导致页面挂起 [英] cURL causing page to hang

查看:164
本文介绍了cURL导致页面挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用当前代码尝试使用cURL异步执行两个脚本。每个脚本托管在不同的域上,大约需要30秒才能完成。我希望这些内容在后台运行,以便页面继续加载,但是一直挂着直到完成。在思考cURL的工作方式时,我完全错了吗?还是我只是做错了什么?

I'm using the current code to attempt to use cURL to asynchronously execute two scripts. Each script is hosted on a different domain and take ~30 seconds to complete. I'm wanting these to run in the background so that the page continues to load, but it's hanging until they complete. Am I completely wrong in my thinking of how cURL works? Or did I just do something wrong?

更新:

$.ajax({
    type    : 'POST',
    url     : 'ajax.php?mode=process',
    data    : '$url',
    complete: function(data)
    {
        $('#test'+num).append('Operation successful.');
    }
});

Num是div的ID。它们是通过代码生成的。所有这些工作正常,除了cURL锁定服务器直到完成文件处理为止。

Num is the ID of the div. They're generated through code. All this works properly, except that cURL locks the server until it's finished processing the files.

下面的代码现在位于另一页上,专门用于处理从URL传入的URL。

The code below is now on another page specifically for processing the URLs passed in from the jQuery ajax call above.

$cURLs = array(
    "script_url?param1=1&param2=2",
    "script_url?param1=5&param2=6");
$result = array();
$mh = curl_multi_init();

foreach ($data as $id => $d) 
{
    $cURLs[$id] = curl_init();
    $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
    curl_setopt($cURLs[$id], CURLOPT_URL,            $url);
    curl_setopt($cURLs[$id], CURLOPT_HEADER,         0);
    curl_setopt($cURLs[$id], CURLOPT_RETURNTRANSFER, 1);

    if (is_array($d)) 
    {
            if (!empty($d['post'])) 
            {
                    curl_setopt($cURLs[$id], CURLOPT_POST,       1);
                    curl_setopt($cURLs[$id], CURLOPT_POSTFIELDS, $d['post']);
            }
    }

    if (!empty($options))
            curl_setopt_array($cURLs[$id], $options);

    curl_multi_add_handle($mh, $cURLs[$id]);
}

$running = null;
do 
{
    curl_multi_exec($mh, $running);
} while($running > 0);

foreach($cURLs as $id => $c) 
{
    $result[$id] = curl_multi_getcontent($c);
    curl_multi_remove_handle($mh, $c);
}

curl_multi_close($mh);
echo "<pre>" . print_r($result, 1) . "</pre>";


推荐答案

不幸的是,直到脚本完成,页面才会完成加载完成执行。即使使用cURL多功能,也仅在脚本运行时才有用。

Unfortunately, your page will not finish loading until your script finishes executing. Even if you use cURL Multi functions, that is only good for when the script is running.

如果需要在后台运行脚本,则必须找到另一种方法,例如在数据库中排队一个下载作业,然后cron运行脚本以每分钟检查一次该队列。

If you need a script to run in the background, you must find another method, such as queuing a download job in a database, and cron running a script to check that queue every minute.

这篇关于cURL导致页面挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆