I am not aware of any function in PHP that does not “block”. Alternatively, and if your server allows such things, you can:
- Use
pcntl_fork() and do other things in the script, waiting for the API call to complete. - Use
exec() to call another script in the background [using & ] to call the API for you if pcntl_fork() not available.
However, if you literally can’t do anything in your script without successfully invoking this API, then it really doesn’t matter whether the call is “blocks” or not. What you really need to worry about is taking so long, expecting this API to exceed the configured max_execution_time , and your script will be interrupted in the middle without proper completion.
$max_calls = 5; for( $i=1; $i<=$max_calls; $i++ ) { $resultJSON = file_get_contents($apiURL); if( $resultJSON !== false ) { break; } else if( $i = $max_calls ) { throw new Exception("Could not reach API within $max_calls requests."); } usleep(250000);
It is worth noting that file_get_contents() has a default timeout of 60 seconds , so you are really threatened by the script being killed. Pay close attention to using cURL as you can set much more reasonable timeout values.
source share