How to properly sanitize URL as a link in PHP? -


i have site users can share link homepage such http://example.com/user. currently, using php function filter_var($_post['url'], filter_validate_url) validate url before adding database using prepared statement.

however, realize php filter function accepts input such http://example.com/<script>alert('xss');</script> used cross-site scripting. counter that, use htmlspecialchars on url within <a> tag , rawurlencode on href attribute of tag.

but rawurlencode causes / in url converted %2f, makes url unrecognizable. thinking of doing preg_replace %2f /. way sanitize url display link?

this outdated :

i using php function filter_var($_post['url'], filter_validate_url) validate url before adding database using prepared statement.

instead of filter_validate_url

you can use 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 valid url'; 

i think may works you. best :)


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -