Simple implementations (2 variants) of the reconnection mechanism for CURL in PHP.
tihoho, 07.2019
Telegram: https://t.me/tihoho
PayPal for beer: [email protected]
Simple implementations (2 variants) of the reconnection mechanism for CURL in PHP.
tihoho, 07.2019
Telegram: https://t.me/tihoho
PayPal for beer: [email protected]
<?php | |
/** | |
* Curl Reconnect (Variant#1: Stop by non-empty content) | |
* @param curlHandler $ch | |
* @param int $tries | |
* @return string | |
*/ | |
function curlReconnect(&$ch, $tries = 3) { | |
try | |
{ | |
foreach(range(0, $tries) as $try) { | |
$response = curl_exec($ch); | |
if(strlen($response)) { | |
return $response; | |
} | |
} | |
return ''; | |
} catch (\Throwable $e) { | |
return ''; | |
} | |
} | |
/** | |
* How to use Variant#1 | |
*/ | |
$ch = curl_init('https://example.com'); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_TIMEOUT, 5); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); | |
// more setopts... | |
$response = curlReconnect($ch, 5); | |
curl_close($ch); | |
// ----------------------------------------------------------------------------------------------- | |
/** | |
* Curl Reconnect (Variant#2: Stop by status code) | |
* | |
* @param curlHandler $ch | |
* @param integer $tries | |
* @param integer $statusCode | |
* @return string | |
*/ | |
function curlReconnect(&$ch, $tries = 3, $statusCode = 200) { | |
try | |
{ | |
foreach(range(0, $tries) as $try) { | |
$response = curl_exec($ch); | |
if($statusCode == (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE)) { | |
return $response; | |
} | |
} | |
return ''; | |
} catch (\Throwable $e) { | |
return ''; | |
} | |
} | |
/** | |
* How to use Variant#2 (same as Variant#1 :) | |
*/ | |
$ch = curl_init('https://example.com'); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_TIMEOUT, 5); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); | |
// more setopts... | |
$response = curlReconnect($ch, 5, 200); | |
curl_close($ch); |