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

Sta*_*tan 48 php arrays

我有控制器从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
Run Code Online (Sandbox Code Playgroud)

如何确保我的数组将取消设置不是很好的所有元素?

Ber*_*rak 80

通过白名单,你的项目期待.

<?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 );
Run Code Online (Sandbox Code Playgroud)

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


Jon*_*Jon 48

您正在寻找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));
Run Code Online (Sandbox Code Playgroud)

看到它在行动.

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

  • @Qmal:`$ good`的好名字称为* values *,而`$ post`的好名字称为* keys *。最简单的解决方法是传入array_flip($ good)而不是$ good,这样两个输入都将好名字作为键。 (2认同)