Add http:// prefix to URL when missing

DiegoP. picture DiegoP. · Jun 5, 2011 · Viewed 39.6k times · Source

Hello I have a very simple code

<a href="'.$aProfileInfo['Website'].'" target="_self">
    <div class="callButton">Website</div>
</a>

The problem is that if the user does not enter http:// the link will then point to my website and not to the external website as it should.

How do I check in PHP if the user has not entered http:// and automatically add it when it is not there?

Answer

David picture David · Jul 15, 2011

I think you'd better use the built in function parse_url() which returns an associative array with its components

something like this will work for you:

 if  ( $ret = parse_url($url) ) {

      if ( !isset($ret["scheme"]) )
       {
       $url = "http://{$url}";
       }
}