Filter array content with whitelist in PHP

Filter array content with whitelist in PHP

Request validation in PHP is quite easy. There are awesome libraries like beberlei/assert. But most functions are geared towards validating if a specific content is available and in the right format.

But what if you want to protect against additional attributes being send. For example if you want to take the full request you get and push it to the database. Then you don't want to have attributes in there you don't need. For cases like those you can use a combination of array_intersect_key and array_flip:

$validAttributes = [
  'id',
  'type',
  'title',
  'content',
  'format',
  'deletedAt',
];

// Remove all keys except the ones in the whitelist
$data = array_intersect_key($requestBody, array_flip($validAttributes));

array_keys transforms array keys with values and the other way round. And array_intersect_key returns an array (from $requestBody) but only with those keys provided in the second array $validAttributes.