Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Will cURL finish in the background, or block all further script execution?

Tags:

php

curl

I'm building an app that at one point curls some contents from an external URL. So far, this has always finished quite quickly/instantly. However, I am unsure as to what would happen if the external server took a long time to respond. Would PHP wait with the execution of the following code until cURL is finished?

I can not really test it because I don't know how to "simulate" a slower response. I hope this pseudo-code makes my question clear:

$ch = curl_init( $some_remote_url );
$fp = fopen( $some_local_file, 'wb' );
curl_setopt( $ch, CURLOPT_FILE, $fp );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_exec( $ch ); // Let's say this takes 20 seconds until the other server responds
curl_close( $ch );
fclose( $fp );
redirect( $some_other_url ); // Will this be executed instantly or only after 20 seconds?

The reason why I am wondering about this is that I would not want my user to look at a "loading" page for 20 seconds in case the remote server was responding slowly, so I would probably have to move the whole process to a cron job. The user doesn't need the result of the curling instantly, so it doesn't matter to him when the process is finished.

like image 843
Louis B. Avatar asked Apr 16 '12 18:04

Louis B.


1 Answers

Curl will block execution. If you want to download the file in background (asynchronously), either use a cron scheduled task, or exec a command like this:

system("wget URL &");
like image 93
kuba Avatar answered Nov 14 '22 22:11

kuba