php - 检查 URL 是否失效或重定向,并不总是有效
问题描述
因此,我正在运行一个 URL 列表以检查它们是否已死或重定向,然后记录结果。我也有一些例外,将重定向到诸如 godaddy.com 或 hugedomains.com 之类的地方的域标记为已死,因为它们基本上是。
我的问题是,它参差不齐。例如,域
- custommarbleproducts.com
- danielharderandsons.com
重定向到这些:
我尝试过滤掉 "?reqp=1&reqr=" 并且它有时会起作用。我可以运行脚本并在十个死/重定向的 URL 中,四个将被标记为死,然后重新运行并有三个或五个标记为死(并且结果不同,上次标记为死的一个可能这次不会) ,我正在寻找更一致的结果。这是功能:
function get_url_status($url) {
$cookie = realpath(dirname(__FILE__)) . "/cookie.txt";
file_put_contents($cookie, "");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
if ($curl = curl_init()) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$final_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
if ((strpos($final_url, "hugedomains.com") !== FALSE) ||
(strpos($final_url, "namecheap.com") !== FALSE) ||
(strpos($final_url, "uniregistry.com") !== FALSE) ||
(strpos($final_url, "afternic.com") !== FALSE) ||
(strpos($final_url, "buydomains.com") !== FALSE) ||
(strpos($final_url, "/?nr=0") !== FALSE) ||
(strpos($final_url, "?reqp=1&reqr=") !== FALSE) ||
(strpos($final_url, "godaddy.com") !== FALSE)) {
return 'dead';
}
if (in_array($http_code, array('404', '403', '500', '0'))) {
return 'dead';
} elseif (($http_code == 200) || ($url == $final_url)) {
return 'ok';
} elseif ($http_code > 300 || $http_code < 400) {
return $final_url;
} else {
return '';
}
}
}
function quote_string($string) {
$string = str_replace('"', "'", $string);
$string = str_replace('&', '&', $string);
$string = str_replace(' ', ' ', $string);
$string = preg_replace('!\s+!', ' ', $string);
return '"' . trim($string) . '"';
}
有没有人有任何想法让这更可靠?
解决方案
也许比较原始和最终 URL 的域:
$orig_host = parse_url($url, PHP_URL_HOST);
$final_host = parse_url($final_url, PHP_URL_HOST);
$len = strlen($orig_host);
if (substr($final_host, 0 - $len) === $orig_host) {
echo "$final_host ends with $orig_host";
}
}
推荐阅读
- php - 使用foreach时如何只显示一次数据
- wildfly - 消息传输过程中的sccp层问题
- scala - Scala 嵌套函数 - 调用
- amazon-ec2 - 通过 RESTful API 公开的云提供商 SLA
- html - 将 div 中的图像元素居中
- java - 如何在 Spring Boot 中编写 Rest API 以下载资源中存在的 Excel 表?
- unix - 如何授予特定用户对 unix 文件的读取权限
- python - Tensorflow 2:获取张量值
- swift - 如何将已知的位置和方向设置为 ARKit 的起点
- apache-kafka - 即使我在 porperties 文件中更改了端口,运行新的 kafka 服务器也会引发异常说端口 9092 alrady in use