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?