• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Automatically unsetting submit values from $_POST + safety issue?

#1
[eluser]Bramme[/eluser]
Hi all,

I've got another question: I love how CI works and how you can so easily reduce work. Atm I've got a little guestbook script going on and the insert code looks like this:

Code:
$insert['datum'] = time();
$insert['IP'] = $this->input->ip_address();    
foreach($_POST as $key => $value) {
    if($key != 'submGb') $insert[$key] = $value;
}
    
$this->db->insert('gastenboek', $insert);
Now with form validation I make sure the fields are trimmed, not empty and the htmlentities function is also applied. Now as you can see, I have to check first if my $key isn't my submit field, else the db class throws an error. Is there any way of preventing this happens? That would make things even easier!

And also: how safe is this code? I'd think pretty safe as I make sure it's the fields are not empty, and the insert function automatically adds slashes too... But a man can never be too sure, so that's why I'm asking.

#2
[eluser]xwero[/eluser]
It's better to hardcode the fieldnames because you don't know if some one is going to temper with the post global. You could do something like this to make it easier on yourself
Code:
$fields = $this->db->list_fields('gastenboek');

$excluded_fields = array('datum','IP','id');

$insert['datum'] = time();
$insert['IP'] = $this->input->ip_address();


foreach ($fields as $field)
{
   if( ! in_array($field,$excluded_fields))
   {
      $insert[$field] = (isset($_POST[$field])?$_POST[$field]:'';
   }
}

The input values are escaped so it's save to add it to the database but for better protection against xss attacks you can use the xss rule in the validation or set the xss cleaning globally or do it in the input->post method.

#3
[eluser]Bramme[/eluser]
that list_fields function is pretty clever! Thanks for this!

#4
[eluser]Bramme[/eluser]
sorry for the double post, but:

come to think of it: isn't the isset($_POST[$field])? etc a bit overkill? I mean, validation checks if there's a value... Or could it still be altered?

#5
[eluser]xwero[/eluser]
it's very easy to post a form with tempered values and keys. There is even a developer firefox add-on that makes it possible to post a form.

The validation only picks up the fields you have added, it doesn't care about the other fields in the post array.

the isset check could be moved up, then you get this
Code:
if( ! in_array($field,$excluded_fields) && isset($_POST[$field]) )
{
   $insert[$field] = $_POST[$field];
}
It is better because then you only add the values that exist in the post field an not all fields in the post array.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.