0

I do validation when saving data to database like following:

$data = validate($data);
update_post_meta($post_id, 'my_post_meta', $data);

The question is, do I need to do validation again when read the data from database?

$data = get_post_meta($post_id, 'my_post_meta');
$data = validate($data); // Do validation again?

1 Answer 1

3

The short answer is "yes", the longer answer is "it depends".

Why do you need to validate? because if you have code, which if used with wrong parameters will delete wordpress (very bad example I know), you should made double sure that it is not triggered by some DB corruption, or more likely, misbehaving filter.

Lets look at this code which handles the state of nuclear weapons under trump ;) which can have the values "dormant", "ready" and "engaged". You might think that this code is enough

switch ($nuclear_state) {
  case 'dormant':...
    break;
  case 'ready':....
    break;
  default : fire();
}

Hopefully no one in his right mind will use the nuclear war option as default in his code, but I hope that this servers as a good illustration as to the risk.

Your code should be

switch ($nuclear_state) {
  case 'dormant':...
    break;
  case 'ready':....
    break;
  case 'engaged' : fire();
    break;
  default : exception('something is wrong with the system, notify admin');
}

And simply refuse to act on bad values.

This is why you should write code that does things, in separate from the code that handles getting the parameters for it. When you have an API like

function nuclear_state_change(string $state) {}

It can easily validate that $state makes sense and raise an exception in a way which is portable between all possible flows that might lead to its call (html, json, ajax, xml-rpc) and let the caller handle the exception.

Obviously it would be better for the caller to validate by itself, but the small overhead in coding is totally worth it especially during development when storing and sending wrong values happens more.

So why the "it depends" answer? If you have a full control of your system, you have audited all code and never install any new plugin or upgrade the theme without fully auditing it, maybe it is just an overhead. But this can probably apply only to small non complex one off projects. For complex projects something bad is much more likely to happen at some point in time, and you do not want it to go unnoticed.

2
  • 1
    +1 for trump, and also DB corruption :)
    – Johansson
    Commented Apr 28, 2018 at 9:13
  • Really enjoyed reading this answer, but it's not for the faint-hearted ;-)
    – birgire
    Commented Apr 29, 2018 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.