【发布时间】:2015-12-23 15:30:56
【问题描述】:
我正在使用代理。无论出于何种原因,假设代理失败,我假设如果返回 403;我想用另一个(来自数组)替换代理。我不确定如何实现它。假设函数顶部有一个代理数组,称为代理
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);,但不确定在哪里添加这个
【问题讨论】:
-
小心调用自己的函数。
-
@ODelibalta 我了解递归函数,但这不仅仅是调用自身的问题,因为该值设置在顶部,虽然变量在末尾有一个新值,但它被重新定义为原值一次调用?不?我很想知道是否有一些解决方法
-
我敢打赌,如果您进一步充实您的问题,您会得到一个很好的答案。例如,也许编写一个递归函数,它可以做你想做的,但不能很好地工作,并寻求帮助来完成它。就像现在一样,你的最终目的还不是很清楚。
-
您本可以这样做并亲自查看最终结果,而不是花时间提出理论问题来问我。只需使用您想要调用它的任何值调用您的函数。
$name=$name."y"; function_name($name)