Page 1 of 1

Check variable for HTTP at the beginning?

Posted: Mon Dec 26, 2005 11:21 am
by VKX
I have a variable, lets say . . . $webaddress. I want to check and see if it starts with "http://"

If it doesn't, I'll stick it in there. I can handle that part, but how can I check for http:// at the beginning of the variable?

Thanks a million!

Posted: Mon Dec 26, 2005 11:26 am
by John Cartwright

Posted: Mon Dec 26, 2005 11:33 am
by MaNiAC
or like this:

Code: Select all

<?
$webaddress = "http://www.site.com";
if( substr($webaddress,0 ,7) == 'http://'){
  echo "does start with http://";
} else {
  echo "does not start with http://<br>";
}
?>

Posted: Mon Dec 26, 2005 12:17 pm
by Chris Corbyn
Well actually... let's say someone posts a link to an FTP site... would you want to replace it with http://ftp://foo.bar ? ;)

This checks simply for a protocol string at the beginning. (Untested)

Code: Select all

//Adds the http:// part to a given URL if not found
//  If the optional second parameter is specified that
//  protocol is used instead.
function addProtocol($url, $prot='http')
{
    if (!preg_match('@^\w+://@', $url)) //Check for for the protocol
    {
        $url = $prot.'://'.$url; //Set one if not found
    }
    return $url;
}
EDIT | ftp may have been a bad example depending upon where this is used, https would be more sensible.