如何使用PHP检查URL是外部URL还是内部URL? [英] How To Check Whether A URL Is External URL or Internal URL With PHP?
本文介绍了如何使用PHP检查URL是外部URL还是内部URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
foreach($ html-> find(' a [href!=#]')as $ ahref){
$ ahrefs ++;
}
我想做这样的事情:
foreach($ html-> find('a [href!=#]')as $ ahref){
if(isexternal $ ahref)){
$ external ++;
}
$ ahrefs ++;
}
其中isexternal是一个函数
function isexternal($ url){
// FOO ...
//测试如果链接是内部/外部
if(/ * condition is true * /){
return true;
}
else {
return false;
}
}
帮助!
解决方案
使用 parse_url 并将主机与您的本地主机进行比较(通常但并不总是与 $ _ SERVER ['HTTP_HOST']
相同)
function isexternal($ url){
$ components = parse_url($ url);
return!empty($ components ['host'])&& strcasecmp($ components ['host'],'example.com'); //空主机将指示url像'/relative.php'
}
Hovewer this将www.example.com和example.com视为不同的主机。如果您希望将所有子域名视为本地链接,那么该函数将会更大一些:
function isexternal($ url) {
$ components = parse_url($ url);
if(empty($ components ['host']))return false; //我们将像/relative.php一样将URL视为相对
if(strcasecmp($ components ['host'],'example.com')=== 0)return false; // url主机看起来完全像本地主机
返回strrpos(strtolower($ components ['host']),'.example.com')!== strlen($ components ['host']) - strlen ( '.example.com的'); //检查url主机是否是子域
}
I'm getting all ahrefs of a page with this loop:
foreach($html->find('a[href!="#"]') as $ahref) {
$ahrefs++;
}
I want to do something like this:
foreach($html->find('a[href!="#"]') as $ahref) {
if(isexternal($ahref)) {
$external++;
}
$ahrefs++;
}
Where isexternal is a function
function isexternal($url) {
// FOO...
// Test if link is internal/external
if(/*condition is true*/) {
return true;
}
else {
return false;
}
}
Help!
解决方案
Use parse_url and compare host to your local host (often but not always it's the same as $_SERVER['HTTP_HOST']
)
function isexternal($url) {
$components = parse_url($url);
return !empty($components['host']) && strcasecmp($components['host'], 'example.com'); // empty host will indicate url like '/relative.php'
}
Hovewer this will treat www.example.com and example.com as different hosts. If you want all your subdomains to be treated as local links then the function will be somewhat larger:
function isexternal($url) {
$components = parse_url($url);
if ( empty($components['host']) ) return false; // we will treat url like '/relative.php' as relative
if ( strcasecmp($components['host'], 'example.com') === 0 ) return false; // url host looks exactly like the local host
return strrpos(strtolower($components['host']), '.example.com') !== strlen($components['host']) - strlen('.example.com'); // check if the url host is a subdomain
}
这篇关于如何使用PHP检查URL是外部URL还是内部URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文