0

Is using a foreach safe to do or does this open up for more security leaks?

<?php

    foreach ($_POST as $key=>$value){
        $_POST[$key] = htmlspecialchars($_POST[$key]);
    }

?>


<form method="POST" action="">
    <input type="text" name="test" value="<?=isset($_POST['test'])?$_POST['test']:''?>"/> 
    <input type="submit" />
</form>

VS.

<?php
     $_POST['test'] = htmlspecialchars($_POST['test']);
?>


<form method="POST" action="">
    <input type="text" name="test" value="<?=isset($_POST['test'])?$_POST['test']:''?>"/> 
    <input type="submit" />
</form>
Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115
  • `foreach` does not open up more security leaks, or else we would all be in trouble.. If you think that this could then you might want to read up on sanitization of data. – SamV Dec 03 '13 at 21:31
  • you should never be changing values in $_POST anyways. you do your escaping/sanitizing at the place where that escaping/sanitizing NEEDs to be performed, Not at the beginning where you don't know HOW the data is going to be used. You're basically recreating an html equivalent of magic quotes. – Marc B Dec 03 '13 at 21:32
  • @FruityP I just want to make sure cycling through the $_POST variable is a valid way to get all variables under $_POST. – Arian Faurtosh Dec 03 '13 at 21:32
  • @MarcB Why shouldn't you change variables in `$_POST`, people always say this but I can't figure out why? Is it only because you want to make sure that data stays untouched? – Arian Faurtosh Dec 03 '13 at 21:35
  • I must of misunderstood your question then, apologies. Take a look at this question: http://stackoverflow.com/questions/16659356/is-this-a-good-way-to-sanatize-php-post-inputs – SamV Dec 03 '13 at 21:41

1 Answers1

1

If the user tries to inject an array then htmlentities will generate a notice, you should check for a string before calling it, else:

Notice: Array to string conversion 

I have been using Acunetix(http://www.acunetix.com/), if you can afford it, it showed me flaws in my code

ka_lin
  • 9,329
  • 6
  • 35
  • 56
  • Isn't a $_POST variable always a string? Event when it is a number? – Arian Faurtosh Dec 03 '13 at 21:33
  • 1
    Nope, you can send array more details here http://stackoverflow.com/questions/6152436/posting-array-from-form – ka_lin Dec 03 '13 at 21:35
  • I can change your input name from 'user_name' to 'user_name[$test]' and then post it and I would have an error or your error.log might pile up – ka_lin Dec 03 '13 at 21:36