removing empty values from serialized array

source : wp-hackers digest # 67,26,3,7,8.


Issue : I have an options setting page that uses the register_setting() and
settings_fields() functions to store my data in a serialized array, following the example set by Ozh here : http://planetozh.com/blog/2009/05/handling-plugins-options-in-wordpress-28-with-register_setting/

When this field is unchecked, the key/value pair in the ozh_sample array is completely removed :
<input name="pms_options[option1]" type="checkbox" value="1" <?php if
(isset($options['option1'])) checked('1', $options['option1']); ?> />

When this field is left blank, however, the value is blank, but the key remains :
<input type="text" name="pms_options[affiliateID]" value="<?php echo
(isset($options['affiliateID']) ) ? $options['affiliateID'] : NULL ;
?>

So my question is twofold : why does the checkbox go away completely, and how can I get an empty options array key to go away ? I've tried unsetting it, setting it to NULL, everything I can think of. How can you get rid of an empty value from a serialized array ?


Solution : Your data validation function needs to be smarter.
Your validation function basically looks like this :
function validate($input) {
.. do some stuff to validate $input ..
? ? return $input;
}

This is actually wrong and somewhat unsafe. The $input is untrusted data. What should be returned is trusted data. What if I was to forge a new input of options[bad-thing] = 'malicious' and to send that to your form ? Your validation function isn't validating the "bad-thing" option, so it passed right through, unchecked.

Instead, you should do this :
function validate($input) {
$output = array();
.. do some stuff to validate $input, but copy the validated values
into $output..
? ? return $output;
}

In this way, only the values you are checking make it through the function.
Then, all you have to do for a blank value is to not put it into the $output array at all.

some additional background :

Checkboxes only send data if they are checked. The simplest way to handle this normally is to use empty() -- $checkbox_value = !empty( $_POST['checkbox_field'] );. If you ever need to remove keys with empty values from an array, simply pass the array through array_filter() without a callback.

That said, use the $input/$output technique. It's definitely the appropriate way to leverage a sanitization callback.
 
 
Creative Commons License
This work by maniac.vardhan is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
 
 

0 comments :: removing empty values from serialized array

Post a Comment