使用Curl Multi Exec从CLI生成PHP

时间:2018-12-03 20:30:28

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

在以下http://php.net/manual/en/function.curl-multi-init.php的代码中

如何在第二个请求发出之前添加代码(例如,在curl向Twitter发送请求之前,sleep(5))

致谢

1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0  // I want this to be 5

...

10 % 5 = 0 // I want this to be 5 as well

1 个答案:

答案 0 :(得分: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";
}
?>