I am have a form that requests a user to submit a website and then on a different page I send a mysql query to retrieve that website an and turn it into a link by doing this in PHP (V=5.6)
$link = '<a href=' . $school_website .' target="_blank">' . $school_website . '</a>';
the problem is that when i try to click this link, instead of sending me to www.google.com for example, it directs me to www.mydomain.com/www.google.com.
I fixed it originally by using substr to see if the first part was "www" and if it was adding "http://" to it and it worked but now i realize that not all websites will start out with that.
I have tried googling this problem but Im not quite sure how to word the problem so I am not getting anything.
My apologies if this is a duplicate. I did not see anything here that fits my problem, so any help would be greatly appreciated. Thanks.
Could always check if it has http/s:// with regex, if it hasn't then add http:// and the link will work as it should. Or make it ugly but simple.
Simplest way is to remove any protocol and prepend // - that would mark the link as absolute and adopt your current protocol. Even if it didn't have http/s:// it would work as it should.
$school_website = '//' . str_ireplace(['https://', 'http://'], '', $school_website);
Example: https://google.com
becomes //google.com
google.com
becomes //google.com
www.google.com
becomes //www.google.com
In any of the above cases it would become a absolute url.
A better but longer way would be to validate the url with regex.
You need http://
or https://
at the beginning of the URL of external links - in fact that should be part of your variable "$school_website", and if that one is for example retrieved from a database, that value has to be changed in the database.
Until you add http://
or https://
in front of url. It will remain the relative
Like if you re on www.mydomain.com
and your href
attribute value is www.google.com
, The attribute value remain the relative and will target to you url.