开发者

Is it safe to turn urls into links?

开发者 https://www.devze.com 2023-02-18 21:39 出处:网络
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 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?


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)
        )
    );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消