Check variable for HTTP at the beginning?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
VKX
Forum Commoner
Posts: 41
Joined: Mon Oct 03, 2005 1:43 pm

Check variable for HTTP at the beginning?

Post 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!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

MaNiAC
Forum Newbie
Posts: 20
Joined: Fri Dec 23, 2005 4:20 am

Post 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>";
}
?>
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
Post Reply