0

I'm getting mad writing some code for sanitize the data which come from a form. In the form I have a input field named "sender_countryCode" that could only contains 2 or 3 text characters like USA, FR, EN, ... the following code should block everything different from a string but if i write "my text" in the field nothing pass the filter!

if  (isset($_POST["sender_countryCode"])){
    $var    =   $_POST["sender_countryCode"];
    $var    =   stripslashes($var);
    $var    =   htmlentities($var);
    $var    =   strip_tags($var);
    $var    =   filter_var($var, FILTER_SANITIZE_STRING);
    $sender["countryCode"] = $var;
    unset($var);
};
Charles
  • 50,943
  • 13
  • 104
  • 142
Nicolaesse
  • 2,554
  • 12
  • 46
  • 71
  • I don't see anything in your code limiting it to 2-3 characters? `FILTER_SANITIZE_STRING` simply strips tags and optionally encodes, it has nothing to do with limiting the length of the string – andrewtweber Jun 09 '12 at 17:41
  • you're right but let take the max lenght for tomorrow, the main problem is that in the form I write "my string", the code show me $sender["countryCode"] as empty! – Nicolaesse Jun 09 '12 at 17:52
  • 2
    Try using a break point or just `echo $var;` after each statement to see where it is failing. I don't see anything wrong with your code. – andrewtweber Jun 09 '12 at 18:19

1 Answers1

2

This works :) ...sorry im abit late, but i saw it was not answered. Here is my solution.:

function maxLengthCheckUp($this) {
    if ( strlen($this) <= 4){
        return TRUE;
    }
}
if (isset($_POST["sender_countryCode"]) 
  && !preg_match('/\s/',$_POST["sender_countryCode"]) 
  && maxLengthCheckUp($_POST["sender_countryCode"])) {
    $var    =   $_POST["sender_countryCode"];
    $var    =   stripslashes($var);
    $var    =   htmlentities($var);
    $var    =   strip_tags($var);
    $var    =   filter_var($var, FILTER_SANITIZE_STRING);
    $sender["countryCode"] = $var;
    echo $sender["countryCode"];
    unset($var, $sender);
};//end of if(...

CREATE YOUR FORM WITH THE FOLLOWING ELEMENTS:

<input type="text" name="sender_countryCode" id="sender_countryCode" />
<input type="submit" name="Submit" id="Submit" value="Submit" />

submit your form...creating a normal form....just use my php code above. Try it out :)

T30
  • 11,422
  • 7
  • 53
  • 57
AlexWeb
  • 36
  • 2