Tuesday, August 30, 2016

How to add http:// if it's not exists in the URL

Let's say you have some input which is url, and the url doesn't always have protocol on it such as http://, https://, ftp://, ftps:// and so on, and you want to automatically add the protocol with php.

You can detect the existence of the protocol with regular expression and then if not found add the protocol that you want, so it only add only when there is no http://, https://, ftp:// ftps:// on the url.

  $url = 'blogger.com' // this is the input url 

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

  return $url;

It should return http://blogger.com

No comments:

Post a Comment