Search code examples
sqlpostforeachcode-injectionmysql-real-escape-string

For each $_POST variable a mysql_real_escape_string?


For my school homework I have to create a function that uses trim(), htmlspecialchars() and mysql_real_escape_string() to prevent SQL- and HTML injection.

I've been trying for a while but I can't get it to work. I've tried a foreach loop and an extract function. I must be doing something wrong, or missing something.

So far, I've got this: (just to see if the variables are being processed)

foreach ($_Post as $Key => $Value) { $$Key = $Value; echo $$Key."<br>"; }

But it won't return anything.

I can use the trim etc on every variable on its own, but there must be a much easier way.

I've got the $_POST variables 'voorletters', 'tussenvoegsel', 'naam', 'adres', 'huisnummer' (numbers), 'telefoon' (numbers), 'postcode', 'woonplaats', 'geslacht', 'email' and 'wachtwoord' (password).

Please help me :(! I'm a beginner concerning php, so please try to explain thoroughly.


Solution

  • What about this

    foreach($_POST as $key => $value) {
        echo 'Current value in $_POST["' . $key . '"] is : ' . $value . '<br>';
        $_POST[$key] = your_filter($value);
    }
    

    where your_filter() is your function calling trim, htmlspecialchars, etc. :

    function your_filter($value) {
        $newVal = trim($value);
        $newVal = htmlspecialchars($newVal);
        $newVal = mysql_real_escape_string($newVal);
        return $newVal;
    }
    

    Pay attention to the variable name too which is $_POST not $_Post. You don't need to use $$ here, you have the key name in the loop in $key and you can access/replace the value in the array with $_POST[$key]

    EDIT : added an echo to print current value

    EDIT2 : added an example of your_filter() function