删除除我想要的元素之外的所有数组元素?

2022-08-30 09:57:08

我有一个控制器,它从HTML表单中获取post参数,然后将它们发送到模型,该模型将数组插入Cassandra数据库。

它是SQLInjection证明,因为它是NoSQL,但是我担心的是,用户只需模拟100k post参数或只是添加一些我不需要的参数,它将入到数据库中。如何确保只有我需要的值将保留在我的数组中。

例:

$post = ['parent_id', 'type', 'title', 'body', 'tags']; // Good
$post = ['parent_id', 'type', 'title', 'body', 'tags', 'one', 'two', 'three'] // Bad

如何确保我的数组将取消设置所有不在良好示例中的元素?


答案 1

通过将您期望的条目列入白名单。

<?php
$post = array( 
    'parent_id' => 1,
    'type' => 'foo', 
    'title' => 'bar', 
    'body' => 'foo bar', 
    'tags' => 'foo, bar', 
    'one' => 'foo',
    'two' => 'bar',
    'three' => 'qux'
);

$whitelist = array(
    'parent_id',
    'type',
    'title',
    'body',
    'tags'
);

$filtered = array_intersect_key( $post, array_flip( $whitelist ) );

var_dump( $filtered );

无论如何,使用Cassandra作为数据存储当然不是不对你收到的数据进行验证的理由。


答案 2

您正在寻找array_intersect

$good = ['parent_id', 'type', 'title', 'body', 'tags'];
$post = ['parent_id', 'type', 'title', 'body', 'tags', 'one', 'two', 'three'];

print_r(array_intersect($good, $post));

查看实际效果

当然,这个具体的例子没有多大意义,因为它适用于数组,但也有array_intersect_key基于键做同样的事情。