[HTML] How To Strip Characters Before $_Post

Started by
4 comments, last by Madhed 10 years, 4 months ago

I am in the middle of designing my own message system and have ran into an issue. Users are able to inject code into their messages, which is executed next time the page is loaded.

Is there a way to strip all non alpha-numeric characters from a form before it gets sent to $_POST using ether JavaScript or PHP ?

The server I am on does NOT have jquery , node.js or AJAX support.

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Advertisement

I'll just leave this here:

http://coding.smashingmagazine.com/2011/01/11/keeping-web-users-safe-by-sanitizing-input-data/

When rendering untrusted (i.e. user-specified) data, always escape it. Do not rely on the client to escape the data - so do not perform the escaping in Javascript when submitting. Validating data is nice too, but do both.

As of right now I haven't found a way to validate a form until after it's in $_POST.

My attempt at scrubbing the input after post wacko.png


<html>
<?php
 if( isset($_POST["name"]) || isset($_POST["age"]) )
  {
     $x1 = preg_replace('/[^A-Za-z0-9]/', "", $_POST['name'] );
     $x2 = preg_replace('/[^A-Za-z0-9]/', "", $_POST['age'] );
     $_POST['name'] = $x1;
     $_POST['age'] = $x2;
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     }
  else{
  $_POST['name'] = 'null';
  $_POST['age'] = 'null';
  }
?>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST" onsubmit=" ">
<br>
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>
</html>

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Note: You can validate form values in javascript, but only as a convenience for the user. Always (!) validate on the server side too. Javascript can be disabled or altered very easily by the user.

Something like this:


$errors = array();
if (!preg_match('/^\w+$/', $_POST['name]) $errors[] = 'name';
if (!preg_match('/^[1-9]+[0-9]*$/', $_POST['age]) $errors[] = 'age';

if (count($errors) > 0) {
    // display errors to user
}
else {
    // everything ok
}

This is just for validating user input however. If you have something like a free text field and you basically want the user to be able to enter whatever they want you must make sure to sanitize the input before storing it in the database or outputting. There are various functions for this task. mysql_real_escape_string, addslashes, htmlspecialchars, etc. I suggest you become familiar with these concepts. that is validation and sanitization.

This topic is closed to new replies.

Advertisement