PHP filter_var for a URL against XSS attacks
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".
精彩评论