Web Hosting Talk







View Full Version : Lots Of POST variables into an array with foreach?


VolkNet
04-29-2005, 04:20 PM
So I have this page that has a pretty large amount of check boxes which are all submitted to a php page.

I have started doing like $category1 = $_POST['category1'];
but its pretty time consuming.

I think I have seen a way to do it with foreach so that you can save the variables into an array. Something like


foreach($_POST as $name=>$val){
$cats[$name] = $val;
}


Is this possible and if so can you show me? Thanks.

The Prohacker
04-29-2005, 05:02 PM
http://us4.php.net/extract

extract($_POST, EXTR_SKIP);

VolkNet
04-29-2005, 05:34 PM
Wow Thanks! worked like a charm! :)

dumisani
04-30-2005, 04:01 PM
Thanks. That does work like a charm

error404
04-30-2005, 07:03 PM
Using extract is almost as dangerous as enabling register_globals. It will pollute your namespace and can trample on existing configuration variables etc. I'd advise that you do something more constrained so there's less chance of introducing exploits into your code. Try this:

$post_vars = array('category1', 'category2', 'description');
foreach ($post_vars as $k)
{
$$k = (isset($_POST[$k]) ? $_POST[$k] : null);
}

error404
04-30-2005, 07:52 PM
Just a small correction; with EXTR_SKIP, extract() causes less problems than it initially appears to. However, because most people are sloppy and don't initialize their variables, I'd advise using a more specific approach.

VolkNet
05-03-2005, 07:40 PM
This is kinda related. If you dont know what the variable names are (for example from a script that you cannot find the name of the variable being posted, is there a way you can be shown what variables are being posted?

Burhan
05-04-2005, 07:40 AM
Sure there is :


$variables_being_posted = array_keys($_POST);

VolkNet
05-04-2005, 01:41 PM
Thanks a lot.