How to add http if it doesn’t exists in the URL using PHP?

jquery getting url parameters & value

Hi guys , here I am going to share a simple php function which is taken care of our fixing url/links problem by adding http in the url If it does not exists in the url

This function will add http in front of urls which doesnt have.

Contents

Here is the PHP code

function fix_url($url) {
if (substr($url, 0, 7) == 'http://') { return $url; }
if (substr($url, 0, 8) == 'https://') { return $url; }
return 'http://'. $url;
}

Usage

 echo fix_url('www.google.com'); 

Output

 http://www.google.com 

The above solution is very simple and straight forward solution, But parse_url function in php is the best one to find the protocol.

Please don’t forget to share and subscribe to latest updates of the blog. Comments and feedbacks are always welcome!

Thanks!

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

2 thoughts on “How to add http if it doesn’t exists in the URL using PHP?”

Leave a Comment