以下是执行您所要求的功能的功能,其中参考了 Stack Overflow 答案,其中提供了您需要的详细信息。
第一:
使用 PHP 标准 filter_var Validate(和 Sanitise)函数解析 URL。您可能还需要确保正确定义方案。
第二,
运行 PHP cURL 请求以获取完整 URL 的 HTTP 标头,然后是站点 URL。 Source.
$url = 'http://www.example.com/folder/file.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo 'HTTP code: ' . $httpcode;
第三
如果$httpcode 返回 200,那么它是一个很好的工作链接,否则我们需要将链接切断到该站点并重新检查该站点(仍然)是否存在。您可以使用Parse_url 执行此操作。 Source。
so:
if($httpcode == 200){
//works
}
if($httpcode >= 400 ){
/*** errors 400+ ***/
$siteUrlParts = parse_url($url);
$siteUrl = $siteUrlParts['scheme']."//".$siteUrlParts['host'];
}
else {
//some other header, up to you how you want to handle this.
// could be a redirect 302 or something...
}
注意schema 部分很重要,而不仅仅是host 部分。
第四
就是这样,使用新的工作 URL 更新数据库行。
齐心协力:
function get_header_code($url){
/***
cURL
***/
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}
function clean_url($link){
$link = strtolower($link);
$link = filter_var($link, FILTER_SANITIZE_URL);
if(substr($link,0,8) !== "https://" && substr($link,0,7) !== "http://"){
$link = "http://".$link;
}
if(filter_var($link, FILTER_VALIDATE_URL) === FALSE){
/***
Invalid URL so clean and remove.
***/
return false;
}
$httpCode = get_header_code($link);
if($httpCode == 200){
/***
works, so return full URL
***/
return $link;
}
if($httpcode >= 400 ){
/*** errors 400+ ***/
$siteUrlParts = parse_url($link);
$siteUrl = $siteUrlParts['scheme']."://".$siteUrlParts['host'];
if(get_header_code($siteUrl) == 200){
/***
Obviously you can add conditionals to accept if it is a
redirection but this is a basic example
***/
return $siteUrl;
}
return false;
}
else {
/***
some other header, up to you how you want to handle this.
could be a redirect 301, 302 or something...
***/
return false;
}
}
然后运行它:
/***
returns either false or the URL of a working domain from the Db.
***/
$updateValueUrl = clean_url($databaseRow['url']);
这对你来说可能不是很完美,但应该为你提供一个良好的基础,让你可以做出你想要的行为。一旦这到位,您就可以运行 PHP MySQL 循环来一次抓取每个 URL(在 LIMIT 批次中,可能是 500 或 1000 个),并使用 foreach 循环遍历每个 URL,并使用这些函数的输出更新每个 URL .