1

I'm currently writing a PHP script for a guestbook in PHP where people can put their name, website and messages in a form, but I want to prevent someone from putting javascript:// in de url box to reduce the risk of XSS, I've tried to solve this with:

<?php filter_var($_POST['website'], FILTER_VALIDATE_URL) ?>

But I'm still able of putting javascript:// in de url box how could I prevent this?

1
  • 1
    Because that is a valid url. You'd have to parse the url and check what protocol is being used. Commented Mar 20, 2012 at 18:37

3 Answers 3

3

A clean solution would be using PHP's parse_url function and to check if the used protocol is HTTP or in a list of allowed protocols if you're allowing http:// and skype:// for example…

$url = 'http://username:password@hostname/path?arg=value#anchor';
$tmp = parse_url($url);

if ($tmp['scheme'] === 'http') {
  echo 'is http://';
}

if (in_array($tmp['scheme'], array('http', 'skype', 'call')) {
  echo 'is allowed protocol';
}
Sign up to request clarification or add additional context in comments.

Comments

2
$chk = parse_url($url);

switch ($chk['scheme']) {
case 'http':
case 'https':
    break;
default:
    // throw error here
    break;
}

Comments

-1

with preg_replace

$website = preg_replace("/(javascript:\/\/)/i", "http://", mysql_real_escape_string($_POST['website']));

or with str_ireplace

$website = str_ireplace("javascript:", "http:", mysql_real_escape_string($_POST['website']));

1 Comment

If $Website is put into a <a href=""></a> your replacing is circumvented if you html encode any of the letters in javascript. java&#115;cript:alert(1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.