Skip to content
Advertisement

Check proxy before cURL

I need to check whether the selected $proxy is active or not and do a loop until a working one in proxy.txt is found before using it in a cURL. How could I do that? Below is a given proxy function.

<?php

function proxies()
{
  $proxylist = file("proxy.txt");
  $randomproxy = rand(0, sizeof($proxylist) - 1);
  $proxylist = $proxylist[$randomproxy];
  $words = explode(':', $proxylist);
  return $words;
}
$proxy = proxies();

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'url');
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
curl_setopt($ch, CURLOPT_PROXY, $proxy[0]);
curl_setopt($ch, CURLOPT_PROXYPORT, $proxy[1]); 
curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$username:$password");
....
?>

Thank you.

Advertisement

Answer

maybe you can ping, something like this

function proxies()
{
    return file("proxy.txt");
}

foreach ($proxies() as $proxy) {
    $item = explode(':', $proxy);
    $waitTimeoutInSeconds = 1;
    
    if ($fp = fsockopen($item[0], $item[1], $errCode, $errStr, $waitTimeoutInSeconds)){   
       $ch = curl_init();

       curl_setopt($ch, CURLOPT_URL, 'url');
       curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
       curl_setopt($ch, CURLOPT_PROXY, $proxy[0]);
       curl_setopt($ch, CURLOPT_PROXYPORT, $proxy[1]); 
       curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$username:$password");

       break;
    }
}  

fclose($fp);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement