Skip to content

Instantly share code, notes, and snippets.

@tihoho
Last active July 11, 2019 20:10
Show Gist options
  • Save tihoho/a4b15e5381db5af8c6a8be5b41652948 to your computer and use it in GitHub Desktop.
Save tihoho/a4b15e5381db5af8c6a8be5b41652948 to your computer and use it in GitHub Desktop.
Simple realization of "reconnect" for php-cURL

PHP cURL reconnect

Simple implementations (2 variants) of the reconnection mechanism for CURL in PHP.

tihoho, 07.2019
Telegram: https://t.me/tihoho
PayPal for beer: tihoho@yandex.ru
<?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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment