Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all array elements except what I want?

Tags:

arrays

php

I have controller that takes post parameters from HTML form, it will then send them to model that will insert the array into Cassandra database.

It is SQLInjection proof, because it's NoSQL, however what I'm afraid is that user can just simulate 100k post parameters or just add some that I don't need and it will be inserted into database. How can I make sure that only the values I need will stay in my array.

Example:

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

How do I make sure that my array will unset all the elements that are not in good example?

like image 832
Stan Avatar asked Apr 12 '12 11:04

Stan


People also ask

How do you remove all elements from an array except first?

You can use splice to achieve this.

How do you exclude an item from an array?

The Problem. If you want to remove an item from an array, you can use the pop() method to remove the last element or the shift() method to remove the first element.

How do you delete an element of one array from another array?

For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter.


1 Answers

By whitelisting the entries you do expect.

<?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 ); 

Anyway, using Cassandra as a data-store is of course not a reason not to do validation on the data you're receiving.

like image 57
Berry Langerak Avatar answered Sep 22 '22 11:09

Berry Langerak