External Links in CodeIgniter

Go To StackoverFlow.com

2

I have the following code:

<div><strong>Name: </strong><?php echo anchor('http://'.$link, $row->Name); ?></div>

Which takes a users input for a link ($link) and puts the url into an anchor tag. It, however, is not redirecting to the external link but simply amending the base url for the site with the stored URL. I attempted to add 'http://' to the beginning of the submitted link which works unless the user has already supplied http in the link input. Any advice on how to overcome this would be amazing.

2012-04-05 00:06
by Julian25
What version of CodeIgniter are you using? I just tried this in version 2.1 and the anchor() function does indeed check that it's external URL before creating application specific ones - cchana 2012-04-05 12:03


5

Yes, per the documentation, anchor() creates links based on your site's URL.

If things are working as expected when URL's are prefixed with http://, but you're having trouble with users sometimes adding http:// and sometimes not, you could simply check the link to determine whether it's ok, or if you need to prefix it. Here's a basic example using strpos:

if(strpos($link, 'http') === FALSE){
    // link needs a prefix...
    $link = 'http://' . link;
} else {
    // link is ok!
}

...use CodeIgniter's prep_url() function (thanks to @cchana for reminding me of it!):

This function will add http:// in the event that a scheme is missing from a URL. Pass the URL string to the function like this:

$url = "example.com";

$url = prep_url($url);
2012-04-05 04:04
by Colin Brock
Or you could use CodeIgniter's prep_url() function that takes care of it for yo - cchana 2012-04-05 07:43
@cchana: Ah, you're right! I thought there was a CI function for this but couldn't remember what it was. I'll add it to my answer. Thanks - Colin Brock 2012-04-05 11:42
Ads