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?

1
  • 1
    Well, it's not a valid URL. The protocol prefix is not optional, if the hostname is to be detected as such. Commented Dec 23, 2012 at 11:32

4 Answers 4

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;

Sign up to request clarification or add additional context in comments.

1 Comment

In a second thought, you don't have a component separator, so only the second option left.
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"
}

1 Comment

In some cases wont work. In your example filter_var checks not only mising schema
4

Just add a default scheme in that case:

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

1 Comment

This is not a particularly robust piece of code though, is it?
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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.