Reputation: 608
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?
Upvotes: 4
Views: 5264
Reputation: 1145
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
Upvotes: 0
Reputation: 11447
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"
}
Upvotes: 5
Reputation: 26730
Just add a default scheme in that case:
if (strpos($host_name, '://') === false) {
$host_name = 'http://' . $host_name;
}
$parse = parse_url($host_name);
Upvotes: 4
Reputation: 12059
Upgrade your php.
5.4.7 Fixed host recognition when scheme is ommitted and a leading component separator is present.
Add scheme manually: if(mb_substr($host_name, 0, 4) !== 'http') $host_name = 'http://' . $host_name;
Upvotes: 5