簡體   English   中英

使用Curl Multi Exec從CLI生成PHP

[英]PHP from CLI using Curl Multi Exec

在以下來自http://php.net/manual/zh/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專家,也不是熟練的程序員: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";
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM