【问题标题】:PHP from CLI using Curl Multi Exec来自 CLI 的 PHP 使用 Curl Multi Exec
【发布时间】:2019-05-05 04:45:27
【问题描述】:

下面的代码来自http://php.net/manual/en/function.curl-multi-init.php

如何在 curl 向 twitter 发出请求之前添加代码(即 sleep(5))

问候

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "https://www.google.com");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "https://twitter.com");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
?>

【问题讨论】:

    标签: php function sockets curl command-line-interface


    【解决方案1】:

    在这方面我不是 PHP 人或称职的程序员 :D 现在免责声明已经发布,这是我的解决方案。

    可能有一种更简洁的方法可以做到这一点,但我对 PHP 和如何扩展类的了解有限。出于这个原因,我决定使用内置的流程控制扩展并创建一个辅助函数来处理 curl 流程。不过,我确信有更好的程序员准备提供更清洁的解决方案。

    <?php
    
    // Helper function
    function async_curl($url,$delay){
        sleep($delay);
        echo "FORK: Getting $url after $delay seconds\n";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
        // Mute the return for demonstration purposes.
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        curl_close($ch);
    }
    
    $urls = array("http://google.com","http://twitter.com","http://www.facebook.com");
    
    foreach($urls as $url){
        // Generate random timeout for demonstration purposes.
        $delay = rand(1,20);
    
        // Create a forked child process for each URL
        $pid = pcntl_fork();
    
        // Exit if fork failed
        if ($pid == -1) {
            exit("Error, failed to create a child process for the URL: $url");
    
        // Create a single child process to call the helper function
        } else if ($pid == 0) {
            echo "MAIN: Forking process for $url\nPID: " .getmypid() . "\tDelay: $delay\n";
            async_curl($url,$delay);
            exit();
        }
    }
    
    // Wait for all forked processes to complete before exiting.
    while (($pid = pcntl_waitpid(0, $status)) > 0) { 
        echo "MAIN: Process $pid completed\n";
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-23
      • 2011-04-25
      • 1970-01-01
      • 2018-10-14
      • 2023-03-03
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      相关资源
      最近更新 更多