开发者

PHP filter_var for a URL against XSS attacks

开发者 https://www.devze.com 2023-01-07 15:26 出处:网络
Here is my function:开发者_如何学编程 function is_url($url) { return (preg_match(\'#^(https?):\\/\\/#i\', $url) && (filter_var($url, FILTER_VALIDATE_URL) !== FALSE));

Here is my function:

开发者_如何学编程
function is_url($url) {
    return (preg_match('#^(https?):\/\/#i', $url) && (filter_var($url, FILTER_VALIDATE_URL) !== FALSE));
}

And here is a nice url that it validates as true:

http://blah.com"onclick="alert(document.cookie)

Imagine if that goes into <a href="<?php echo $url; ?>">

Are there any better URL validators with regex? Or is the URL I am testing with actually a valid URL (in which case I would need an XSS clean up function)?


There's this built-in filter:

filter_var($url, FILTER_VALIDATE_URL);

This will return false with your example URL. If it were valid, it would return $url. Example:

glopes@nebm:~$ php -r "var_dump(filter_var('http://blah.com\"onclick=\"alert(document.cookie)', FILTER_VALIDATE_URL));"
bool(false)

Anyway, the solution to prevent XSS is to use htmlspecialchars. Since it's an attribute, you should use ENT_QUOTES:

htmlspecialchars($data, ENT_QUOTES);

But you should also validate the URL, because otherwise the user can include javascript:-like "URLs".

0

精彩评论

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