2

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?

1
  • have you considered strip_tags() ? Commented May 9, 2013 at 12:37

3 Answers 3

3

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

this is only a part of the problem. urlencode will spoil other characters as well. so, whole approach with urlencode is wrong.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.