Parse_url()在传递example.com时返回错误



根据以下代码,如果$host_name是类似example.com的东西PHP返回一个通知:Message: Undefined index: host,但在完整的url,如http://example.com PHP返回example.com。我尝试了if语句与FALSE和NULL,但没有工作。

$host_name = $this->input->post('host_name');
$parse = parse_url($host_name);
$parse_url = $parse['host'];

我如何修改脚本以接受example.com并返回它?

  1. 升级你的php5.4.7 Fixed host recognition when scheme is ommitted and a leading component separator is present.

  2. 手动添加方案:if(mb_substr($host_name, 0, 4) !== 'http') $host_name = 'http://' . $host_name;

您可以使用filter_var检查方案是否存在,如果不存在则添加一个

$host_name = 'example.com';
if (!filter_var($host_name, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)) {
    $host_name = 'http://' . $host_name;
}
$parse = parse_url($host_name);
var_dump($parse);
array(2) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(11) "example.com"
}

在这种情况下只需添加一个默认方案:

if (strpos($host_name, '://') === false) {
    $host_name = 'http://' . $host_name;
}
$parse = parse_url($host_name);

这是一个示例函数,无论方案如何,它都返回真实主机。

function gettheRealHost($Address) { 
   $parseUrl = parse_url(trim($Address)); 
   return trim($parseUrl[host] ? $parseUrl[host] : array_shift(explode('/', $parseUrl[path], 2))); 
} 
gettheRealHost("example.com"); // Gives example.com 
gettheRealHost("http://example.com"); // Gives example.com 
gettheRealHost("www.example.com"); // Gives www.example.com 
gettheRealHost("http://example.com/xyz"); // Gives example.com 

相关内容

最新更新