Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run cURL request in the background in PHP?

I'm trying to build some kind of web based download manager using PHP and the cURL extension, I am stuck with one problem though, how can I download and save the file with cURL without having to make the user wait, meaning he will make the request and it will be processed in the background.

Now I can't use system calls (exec, system ... etc) as most of the hosts I work with disable these functions, and the other problem is the max execution time for PHP scripts, but I guess this one can be changed in .htaccess or using ini_set or can it not?

I've read somewhere that setting connect_timeout to 1 will work, but does not that terminate the connection?

One solution is to use cronjobs, after the users submits the file he wants to download, a cronjob will check the database and if there is a file in the queue it will start downloading it, but I thought I want to avoid using cron jobs if possible.

So back to the main question, is there a way to tell the php script to run some certain function in the background and delivering the response to the users regardless of the result of that function

Thanks

like image 273
AL-Kateb Avatar asked Jun 20 '13 11:06

AL-Kateb


People also ask

How does PHP handle cURL request?

curl_setopt( $curl , CURLOPT_POSTFIELDS, $json_string ); curl_setopt( $curl , CURLOPT_HTTPHEADER, array ( 'Content-Type:application/json' )); curl_setopt( $curl , CURLOPT_RETURNTRANSFER, true ); $data = curl_exec( $curl );

How let cURL use same cookie as browser in PHP?

You can't. The only way this would work is if you use persistent cookies in your curl request. CURL can keep cookies itself. Assign a session ID to the cookie file (in curl) so subsequent requests get the same cookies.


2 Answers

I think there have been other posts exploring the options already. Given your constraints, I see two other approaches:

  • Make an asynchronous call with cURL to another script doing the processing (see http://www.paul-norman.co.uk/2009/06/asynchronous-curl-requests/)
  • Use JS to trigger the long running background task from the frontend side
like image 75
joerx Avatar answered Sep 21 '22 17:09

joerx


        function background_curl_request($url, $method, $post_parameters){
            if (is_array($post_parameters)){
                $params = "";
                foreach ($post_parameters as $key=>$value){
                    $params .= $key."=".urlencode($value).'&';
                }
                $params = rtrim($params, "&");
            } else {
                $params = $post_parameters;
            }
            $command = "/usr/bin/curl -X '".$method."' -d '".$params."' --url '".$url."' >> /dev/shm/request.log 2> /dev/null &";
            exec($command);
        }
like image 29
Monkeypox Avatar answered Sep 20 '22 17:09

Monkeypox