Question

According to following code if $host_name is something like example.com PHP returns a notice: Message: Undefined index: host but on full URLs like http://example.com PHP returns example.com. I tried if statements with FALSE and NULL but didn't work.

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

How can I modify the script to accept example.com and return it?

Was it helpful?

Solution

  1. Upgrade your php. 5.4.7 Fixed host recognition when scheme is ommitted and a leading component separator is present.

  2. Add scheme manually: if(mb_substr($host_name, 0, 4) !== 'http') $host_name = 'http://' . $host_name;

OTHER TIPS

You could just check the scheme is present using filter_var and prepend one if not present

$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"
}

Just add a default scheme in that case:

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

this is a sample function that returns the real host regardless of the scheme..

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top