Jump to content

Javascript being executed in PHP... problems.


Cless

Recommended Posts

Hello.

 

Is there a way to remove javascript scripts and the sort from PHP strings? I have a sign up script, which escapes the information (so the name <b>Blah'1</b> would be <b>Blah\'1</b>). However, when you are logged in, and you go to a page that displays your username, it utilizes the "stripslashes()" function so it doesn't display <b>Blah\'1</b>.

 

Anyway, if somebody signs up with the username <b><script>alert('Blah');</script></b>, it will create an alert message saying 'Blah'.

 

Basically, I was wondering if there was a way to remove scripts from PHP strings...

 

Thanks!

You should always validate the input of your users, personally I always use regular expression:

 

 

<?php

if(preg_match('/^[a-z0-9_-]+$/i',$_POST['username']) {

   echo 'You have chosen a valid user name';
}
else {

   echo 'You have chosen an invalid user name';
}
?>

 

The above will check if $_POST['username'] only contains letters a-z, numbers 0-9, underscore _ and minus -. This will prevent the scenario you presented since they wont be able to sign up with a nasty username...

 

You can also look at some build-in php functions like strip_tags():

http://dk2.php.net/manual/pl/function.strip-tags.php

Your idea about removing "scripts" from user names (text strings) is a bad idea for two reasons:

 

#1: Your user thinks he can name himself <script>alert('Blah');</script> and then you change it to 'Blah'... the user has his user name "changed" without him knowing or without his consent.

 

#2: Your user clearly didn't think he could call him self <script>alert('Blah');</script>, he thought it could be funny and f*ck up your site, so he probably wont be using it, so you will have tons of weird user names floating around in your user system.

 

Just make a set of rules and present them to the user when he wants to create an account. Only letters a-z, numbers 0-9 or similar... maybe some specials chars too and space. Then validate the input and if it doesn't fit the rules prompt the user before the account is created.

 

But of course it's a choice you have to make. I only wonder about it when it comes to validating / cleaning user input such as forum posts, contact forms ect... Should I remove scripts completely (if it's not a code related site) or should i convert them to HTML entities and just display them?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.