我正在使用代理。無論出於何種原因,假設代理失敗,並且假設這是403返回的;我想用另一個(來自數組)替換代理。我不能確定如何實現它。假設有在函數的頂部代理陣列稱爲代理使用返回變量的值重新啓動PHP函數
public static function get_http_response_code($url, &$redirect = null, $proxy = '23.244.68.94:80') {
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) return false;
if (!is_null($proxy)){
$useragent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36";
$ch = curl_init();
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$header = curl_exec($ch);
curl_close($ch);
}
// Pattern to find the status code
$codepattern = '/[0-9]{3}/';
preg_match($codepattern, $header, $codematch);
// Pattern to find the redirect link
$linkpattern = '/https?:\/\/(.+)\//';
preg_match($linkpattern, $header, $linkmatch);
// Store results in an array
$statuscode = (array_values($codematch)[0]);
// Store the redirect link in the $redirect variable
if ($statuscode == 301 || $statuscode == 302 || $statuscode == 303) {
if (strpos(array_values($linkmatch)[0], 'http') !== false) {
$redirect = array_values($linkmatch)[0];
} else {
}
}
return $statuscode;
}
$statuscode
將返回代碼。如果它是403,我想從數組中獲得下一個代理並重新啓動該函數。我想這樣做$proxy = next($proxies);
的只是不確定在哪裏添加此
讓它靜態的。 – Rizier123
[遞歸函數](http://stackoverflow.com/questions/2648968/what-is-a-recursive-function-in-php) – ODelibalta
小心使用自己調用的函數。 – crmpicco