PHP

Prefix URL With Protocol In PHP

Here is a useful function I use in many of my applications, it will take a URL and see if it's prefixed with a protocol, if it's not then it will add the default prefix to the start of the string.

This function will search for http://, https://, ftp:// and ftps://, if none of them are in the string then we add the prefix to the start of the string.

By default the prefix is set to http:// but you can pass in a second parameter to change the default prefix protocol to anything you want.

function prefix_protocol($url, $prefix = 'http://')
{
    if (!preg_match("~^(?:f|ht)tps?://~i", $url))
    {
        $url = $prefix . $url;
    }

    return $url;
}

Below are the different results you can return from the prefix protocol function.

// returns http://paulund.co.uk
prefix_protocol('paulund.co.uk');

// returns https://paulund.co.uk
prefix_protocol('paulund.co.uk', 'https://');

// returns ftp://paulund.co.uk
prefix_protocol('paulund.co.uk', 'ftp://');

// returns ftps://paulund.co.uk
prefix_protocol('paulund.co.uk', 'ftps://');

// returns http://paulund.co.uk
prefix_protocol('http://paulund.co.uk');

// returns https://paulund.co.uk
prefix_protocol('https://paulund.co.uk');

// returns ftp://paulund.co.uk
prefix_protocol('ftp://paulund.co.uk');

// returns ftps://paulund.co.uk
prefix_protocol('ftps://paulund.co.uk');
Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial