How to force an HTML link to be absolute?

46,813

Solution 1

If you prefix the URL with // it will be treated as an absolute one. For example:

<a href="//google.com">Google</a>.

Keep in mind this will use the same protocol the page is being served with (e.g. if your page's URL is https://path/to/page the resulting URL will be https://google.com).

Solution 2

Use a protocol, preferably http://

<a href="http://www.google.com">Google</a>

Ask users to enter url in this format, or concatenate http:// if not added.

If you prefix the URL only with //, it will use the same protocol the page is being served with.

<a href="//google.com">Google</a>

Solution 3

I recently had to do something similar.

if (strpos($url, 'http') === false) {
    $url = 'http://' .$url;
}

Basically, if the url doesn't contain 'http' add it to the front of the string (prefix).

Or we can do this with RegEx

$http_pattern = "/^http[s]*:\/\/[\w]+/i";

if (!preg_match($http_pattern, $url, $match)){  
   $url = 'http://' .$url;
}  

Thank you to @JamesHilton for pointing out a mistake. Thank you!

Share:
46,813
Arnaud
Author by

Arnaud

Updated on August 12, 2021

Comments

  • Arnaud
    Arnaud almost 3 years

    In my website, users can put an URL in their profile.

    This URL can be http://www.google.com or www.google.com or google.com.

    If I just insert in my PHP code <a href="$url">$url</a>, the link is not always absolute.

    How can I force the a tag to be absolute ?

  • Edward Comeau
    Edward Comeau over 7 years
    You should also mention that if the absolute URI is specified with the two forward slashes only, then the protocol of the current site will be used when connecting to the profile url, i.e. yoursite.net will result in google.com, while yoursite.net will result in google.com
  • Marco Chiappetta
    Marco Chiappetta over 7 years
    Yes, which suits the case in the question. By the way your links are broken (parsed).
  • James Hilton
    James Hilton over 7 years
    This will always return false because if it finds http at the beginning of $url, it will return a 0 because the position of the string 'http' starts at index 0. 0 is considered falsey in the if statement, so you need to use the === operator instead.
  • StephanieQ
    StephanieQ over 7 years
    @JamesHilton Aw jeez how embarrassing! Fixed, thank you!
  • DeepBlue
    DeepBlue over 7 years
    This does not work if your website protocol is different from the url protocol. If your website is https then http url will not work because it will be given https instead.
  • eddy85br
    eddy85br over 6 years
    Maybe it would be a better RegExp if you use: "/^https?:\/{2}\w/i"