4

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?

Zim3r
  • 580
  • 2
  • 14
  • 36
  • 1
    Well, it's not a valid URL. The protocol prefix is not optional, if the hostname is to be detected as such. – mario Dec 23 '12 at 11:32

4 Answers4

5
  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;

Alex
  • 11,479
  • 6
  • 28
  • 50
  • 2
    In a second thought, you don't have a component separator, so only the second option left. – Alex Dec 23 '12 at 11:11
5

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"
}
Crisp
  • 11,417
  • 3
  • 38
  • 41
4

Just add a default scheme in that case:

if (strpos($host_name, '://') === false) {
    $host_name = 'http://' . $host_name;
}
$parse = parse_url($host_name);
Niko
  • 26,516
  • 9
  • 93
  • 110
0

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 
aimiliano
  • 1,105
  • 2
  • 12
  • 18