Reputation:
I often use the following code on my WordPress builds in order to help prevent invalid links being added:
// add http:// if necessary
function addHttp($url) {
if(substr($url, 0, 4) == 'www.') {
$url = 'http://' . $url;
}
return $url;
}
But this won't work should anyone add a link that does include a 'http://' but doesn't include a 'www.' in there too.
Does anyone know how I can modify my script to cater for this?
Upvotes: 0
Views: 235
Reputation: 197609
You need to check for that and then deal with the case as well, as you did already for the case you deal with.
I normally suggest the NetUrl2
class for URL handling as it makes such tasks extremely easy.
However, you can just do with the following modification, that not only normalizes the other parts you don't cover but also properly checks for the scheme. I've highlighted the part which adds the www.
you asked for so you can easily remove it if you don't need that any longer:
function addHttp($url) {
$parts = parse_url($url);
$modif = function ($key, $prefix, $default = '') use (&$parts)
{
$parts[$key] = isset($parts[$key]) ? $prefix . $parts[$key] : $default;
};
$modif('scheme', '', 'http');
$parts['scheme'] = strtolower($parts['scheme']);
if (isset($parts['path']) && $parts['path'][0] !== '/')
{
$pathIsInPath = strstr($parts['path'], '/', TRUE);
$parts['host'] = $pathIsInPath ? : (isset($parts['host']) ? $parts['host'] : '') . $parts['path'];
$parts['path'] = $pathIsInPath ? substr($parts['path'], strlen($pathIsInPath)) : '';
}
if (isset($parts['port']) && $parts['scheme'] === getservbyport($parts['port'], 'tcp')) {
unset($parts['port']);
}
$modif('path', '', '/');
$parts['path'] === '/' && $parts['path'] = '';
// add www. if wanted
if (substr($parts['host'], 0, 4) !== 'www.') {
$modif('host', 'www.');
}
return sprintf('%s://%s%s%s%s%s', $parts['scheme'], $parts['host'], $modif('port', ':')
, $parts['path'], $modif('query', '?'), $modif('fragment', '#'));
}
Upvotes: -5
Reputation: 943142
www
in it. Adding it will often break URLs.http
or https
and add the scheme if it doesn'tSo:
function addHttp($url) {
if(substr($url, 0, 4) != 'http') {
$url = 'http://' . $url;
}
return $url;
}
Upvotes: 7