HappyDeveloper
HappyDeveloper

Reputation: 12805

Is it safe to turn urls into links?

I want to turn urls in the user comments, into links.

I don't have time to test bloated anti-xss libraries like HTML Purify, so I wouldn't be allowing any html tags.

I just want to make everything go through htmlentities() and nl2br(), and then use preg_replace() to find urls and turn them into links ('a' html tags).

Is it unsafe to grab the urls I find and put them inside href='' ?

If not, what can I do about it?

Upvotes: 1

Views: 176

Answers (1)

NikiC
NikiC

Reputation: 101906

Yes, it should be safe. If you wonder how, here is a function I use for this (I simplified it for the purpose of this post):

function formatPost($string) {
    return nl2br(
        preg_replace_callback(
            '~https?://([^/\s]+)(?:/((?>[/\w]+|\S(?!\s|$))*))?~',
            function($matches) {
                $url  = $matches[0];
                $host = $matches[1];
                $path = isset($matches[2]) ? $matches[2] : '';
                $follow = false;

                if ('' == $path) {
                    $text = $host;
                } elseif ($_SERVER['HTTP_HOST'] == $host) {
                    $text = $path;
                    $follow = true;
                } else {
                    $text = $host . '/' . $path;
                }

                return '<a href="' . $url . '"' . (!$follow ? ' rel="nofollow"' : '') . '>' . $text . '</a>';
            },
            htmlspecialchars($string)
        )
    );
}

Upvotes: 1

Related Questions