Git Hub
Git Hub

Reputation: 45

<a> element messed up with https urls

I have a simple <a> element in my website: href="//<?php echo $link; ?>" target="_blank">LINK

The $link is retrieved off my database. This $link is like: google.com, www.google.com, https://google.com, http://google.com.

I have read that, in order to have absolute href urls, I should prefix the $url with //. But when $link=https://www.google.com The <a> element redirects the browser to https://https//www.fxp.co.il - which is wrong. How can it be fixed?

Upvotes: 1

Views: 47

Answers (2)

giovybus
giovybus

Reputation: 359

Hi you can create a simple function like this:

<a href="<?= getClearUrl($link); ?>" target="_blank">LINK</a>

the function:

function getClearUrl($link){
    if(filter_var($link, FILTER_VALIDATE_URL)){
        return $link;
    }else{
        return "//" . $link;
    }
}

Upvotes: 1

MultiSuperFreek
MultiSuperFreek

Reputation: 416

If $link already contains the https:// or http:// (or //) at the start, then you should not prefix it with another //, but if it doesn't the you should, so maybe check for that before echoing the link.

Upvotes: 0

Related Questions