我有一个数据库,其中包含过去几年收集的制造商url,我需要做一些春季大扫除:
-
有些url像
http://brandname.com/aboutus/
所以我需要删除除主域以外的任何路径,因为许多路径/子目录可能已经过期… -
我希望能够检查这些域名是否真的存在或被域名鲨鱼占用…
我目前正在使用PHP+MySQL
下面是一个函数,用于执行您的请求,并参考Stack Overflow答案,其中给出了您需要的详细信息。
:
使用PHP标准filter_var
Validate(和Sanitise)函数解析URL。您可能还需要确保方案是正确定义的。
,
运行PHP cURL请求获取完整URL的HTTP头,然后是站点URL的HTTP头。源。
$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;
3
如果$httpcode
返回200,那么它是一个良好的工作链接,否则我们需要将链接削减到只是网站,并重新检查网站(仍然)存在。您可以使用Parse_url实现这一点。源。
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。