Is making asynchronous HTTP requests possible with PHP?

前端 未结 5 1405
情歌与酒
情歌与酒 2020-11-27 17:42

I have a PHP script that needs to download several files from a remote server. At the moment I just have a loop downloading and processing the files with cURL, which means t

5条回答
  •  醉话见心
    2020-11-27 18:28

    In PHP 7.0 & Apache 2.0, as said in PHP exec Document, redirecting the output, by adding " &> /dev/null &" at the end of the command, could makes it running on background, just remember to wrap the command correctly.

    $time = microtime(true);
    $command = '/usr/bin/curl -H \'Content-Type: application/json\' -d \'' . $curlPost . '\' --url \'' . $wholeUrl . '\' >> /dev/shm/request.log 2> /dev/null &';
    exec($command);
    echo (microtime(true) - $time) * 1000 . ' ms';
    

    Above works well for me, takes only 3ms, but following won't work, takes 1500ms.

    $time = microtime(true);
    $command = '/usr/bin/curl -H \'Content-Type: application/json\' -d \'' . $curlPost . '\' --url ' . $wholeUrl;
    exec($command . ' >> /dev/shm/request.log 2> /dev/null &');
    echo (microtime(true) - $time) * 1000 . ' ms';
    

    In total, adding " &> /dev/null &" at the end of your command may helps, just remember to WRAP your command properly.

提交回复
热议问题