Reputation: 11275
I have a site where users can share a link to their homepage such as http://example.com/user
. Currently, I am using the PHP function filter_var($_POST['url'], FILTER_VALIDATE_URL)
to validate the URL before adding it to database using prepared statement.
However, I realize that the PHP filter function accepts input such as http://example.com/<script>alert('XSS');</script>
which could be used for cross-site scripting. To counter that, I use htmlspecialchars
on the URL within the <a>
tag and rawurlencode
on the href
attribute of the tag.
But rawurlencode
causes the /
in the URL to be converted to %2f
, which makes the URL unrecognizable. I am thinking of doing a preg_replace
for all %2f
back to /
. Is this the way to sanitize the URL for display as a link?
Upvotes: 2
Views: 3732
Reputation: 261
This is outdated now :
I am using the PHP function filter_var($_POST['url'], FILTER_VALIDATE_URL) to validate the URL before adding it to database using prepared statement.
Instead of FILTER_VALIDATE_URL
you can use the following trick :
$url = "your URL"
$validation = "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
if((bool)preg_match($validation, $url) === false)
echo 'Not a valid URL';
I think it may works for you. All the best :)
Upvotes: 3
Reputation: 2668
Do not allow urls with tags.
A user inserting a tag to a url means its probably malicious. Having "homepages" containing tags is just wrong.
Upvotes: 0
Reputation:
After sanitizing, the URL Use, XSS
related scripts, just change %2f
character using
str_replace('%2f', '/', $result)
after your your code, but before the filter_var()
and it will change it back to its original character. So, your script can go on.
Upvotes: 0