PHP: translate POST into simple variables? - php

I know this is totally wrong, I didn't write the app, I just have to make it work while I work on the new one. Seems like GoDaddy made some updates to our account so now there are some things that don't work. I already turned register globals on and a lot of things went back to normal. Now, this doesn't work...
There is a hidden field <input type="hidden" name="SUBMIT1" value="1" />
There is a check for that field
if($SUBMIT1) {
// this part never gets executed.
}
I know I can easily fix it by doing this instead...
if($_POST['SUBMIT1']) {
// this part never gets executed.
}
The problem is, this is a huge app and it's going to take a loooong time to do that everywhere. Is there a way or a setting I can turn on so that when a form is submitted $_POST['WHATEVER'] also works as $WHATEVER?

You can use extract to get the exact functionality you described:
extract($_POST);
Please note the possible safety issue here: a user could send extra data in $_POST and "overwrite" the values of existing variables in your code. You can pass a second parameter to extract to prevent these problems:
extract($_POST, EXTR_SKIP);
This will skip extracting any fields in the $_POST array that already have matching variables in the current scope.

you can try something like this:
$_POST = array('SUBMIT1' => 'SUBMIT ONE', 'SUBMIT2' => 'SUBMIT TWO');
foreach($_POST as $k => $v) {
define(''. $k. '', $v);
}
echo SUBMIT1; // and so on

foreach ($_POST as $key => $value ) {
if(is_array($value)){
foreach ($value as $k => $v ) {
$$k = $v ;
}
}else{
$$key=$value;
}
echo $key ." : " .$value."<br>";
}

Related

PHP post all form inputs without creating variables for each

Usually when I use PHP I create a variable and post statement for each form input like so:
$myVar1 = $_POST["formItem1"];
$myVar2 = $_POST["formItem2"];
ect......
I know if i use:
echo $_POST;
I can get all the key and values from the form inputs but I don't know how to use them in a script.
So I guess I have 2 questions:
How do I quickly post all form inputs without creating a variable for each input?
How do I use a posted in a script without having it assigned to a specific variable?
To simply echo all the inputs, you can use a foreach loop:
foreach ($_POST as $key => $value) {
echo $value.'<br/>';
}
If you don't want to store them in variables, use arrays:
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
Now, $data is an array containing all the data in $_POST array. You can use it however you wish.
You don't have to assign to a variable. You can use directly $_POST['input_name']
If you want to deal with each sended params, you can use foreach loop:
foreach ($_POST as $key => $val)
{
echo "$key : $val <br/>";
}
for this instance of just quickly checking and testing i typically just use the print_r() function: documentation here
as quoted from the docs:
print_r() displays information about a variable in a way that's readable by humans.
one line easy to toggle on and off (with comments)- no need to use any form of variables
print_r($_POST);
if i need my output nice and readable i like to expand it as follows:
function print_r2($x){
echo '<pre>';
print_r($x);
echo '</pre>';
}
and then you can call with: print_r2($_POST);
this way you get the pre-formatted text block on your html page and can see the line breaks and tabbed spacing provided from the $_POST object printout
Another way to extract (besides the extract function) variables is;
$array = array('foo'); // Which POST variables do you want to get
foreach($array as $key) {
if(!isset(${$key})) { // Check if variable hasn't been assigned already
${$key} = $_POST[$key];
}
}
echo $foo;
I would not recommend it because it can get quite messy to keep up.
View everything in $_POST is useful for debugging
echo '<pre>'.print_r($_POST, true).'</pre>';
Access a specific checkbox
HTML
<input type="checkbox" value="something" name="ckbox[]" checked>
<input type="checkbox" value="anotherthing" name="ckbox[]" checked>
PHP
echo $_POST['ckbox'][0]; // something
echo $_POST['ckbox'][1]; // anotherthing
// isolate checkbox array
$ckbox_array = $_POST['ckbox'];
Define a function that allows you to access a specific $_POST item by name (key):
function get_post_value($name, $default)
{
if ( isset($_POST[$name]) ) {
return $_POST[$name];
} else if ( $default ) {
return $default;
}
return null;
}
$default allows you to pass a value that can be used as a fallback if the key you specify isn't present in the $_POST array.
Now you can reference $_POST items without assigning them to a variable, and without worrying if they are set. For example:
if ( get_post_value('user-login-submit', false) ) {
// attempt to log in user
}
You can use extract($_POST), it will create variables for you.
For example, you can have for the code you posted :
<?php
$_POST["formItem1"] = "foo";
extract($_POST);
echo $formItem1; // will display "foo"
?>
EDIT : it's not PHP explode, it's extract.

Use POST variables without calling them specifically

All,
I have a form that has some text inputs, checkboxes, select box and a textarea. I want to submit the form with PHP using a submit button to a page for processing.
That part is fine but what I would like to do is basically get the results into an array so I can do a foreach loop to process the results.
Basically I'm trying to create a dynamic form the submits to my backend processing script and don't want to hard code in the post values like the following:
$var1 = $_POST['var1'];
echo $var1;
$var2 = $_POST['var2'];
echo $var2;
Does anyone know how to go about doing something like this or give any recommendations?
If there're no other data in your POST but these generated elements, just do
foreach( $_POST as $key => $val ) {
// do your job
}
and process what you have. If you want to mix your generated entries with predefined you may want to put these generated in nested array:
<input ... name="generated[fieldname]" />
and then you iterate
foreach( $_POST['generated'] as $key => $val ) {
// do your job
}
Just use array notation:
<input name="vars[]" value="" />
Then you will have something like this as $_POST:
Array ('vars' => Array(
0 => 'val1'
1 => 'val2'
)
)
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val";
}
Actually, the $_POST variable is an array. you just need to extract the array values by using a simple foreach loop. that's it.
I hope this example help you.
foreach($_POST as $field_name => $val)
{
$asig = "\$".$field_name."='".addslashes($val)."';";
eval($asig);
}
After running this script all the POST values will be put in a variable with the same name than the field's name.

Parsing unknown POST args in PHP

I have an HTML form being populated by a table of customer requests. The user reviews each request, sets an operation, and submits. The operation gets set into a POST arg as follow
$postArray = array_keys($_POST);
[1]=>Keep [2]=>Reject [3]=>Reject [4]=>Ignore ["item id"]=>"operation"
This is how I am parsing my POST args, it seems awkward, the unused $idx. I am new to PHP, is there a smoother way to do this?
$postArray = array_keys($_POST);
foreach($postArray as $idx => $itemId) {
$operation = $_POST[$itemId];
echo "$itemId $operation </br>";
// ...perform operation...
}
foreach ($_POST as $key => $value) // $key will contain the name of the array key
You could use
foreach($_POST as $itemId => $operation ) {
echo "$itemId $operation </br>";
// ...perform operation...
}
instead
http://nz.php.net/manual/en/control-structures.foreach.php
You don't have to use $idx in loop if is not needed.
It might be like that:
foreach($postArray as $itemId) {
...
}
Main problem is the data structure is very messy.
Maybe it's better way to organise form output.
Probably in some well structured associative array.
I can't see the form, I don't know the details so it's hard to tell more.

Cleaning up array elements from a form

I have a form that uses inputs to create and array. The inputs are not all required but at least one is.
<form method="post" action="process.php">
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input class="submitbg" type="submit" value="Register" name="submit"/>
</form>
Now on process.php I want to loop through the array remove two types of special characters : ; then make all upper case, and verify there are only 12 characters and then serialize the arrray.
$my_array = $_POST['MAC'];
foreach ($my_array as $val){
$val = strtoupper($val);
$val = str_replace(";","",$val);
$val = str_replace(":","",$val);
$val = trim($val);
if (strlen($val) != 12)){
$valid = false;
$error = "Your MAC address is not 12 characters long";
}
}
$mac_addresses = serialize($my_array);
// if valid is not false do something with the cleaned up array.
The questions:
Will my foreach loop save the updated values back into the array?
How to check to make sure there is at least one array value?
I am just not sure if my foreach loop updates and resaves the values each time
If you want to save the values you should change your loop so that it looks something like this:
foreach ($my_array as $idx => $val) {
...
$my_array[$idx] = $val;
}
Of course you could also save the proper value to a separate clean array which you will then use further on in your application.
I also have to check to make sure there is at least one entry.
In theory you do not have to check whether the array contains elements to use the array in a foreach. The thing you need to check though is whether the variable contains an array. Suppose the MAC[] field wasn't submitted to the server you would first get a warning (it might also be an error nowadays) because you are looking up some non-existent index in the array. Secondly you would get an error on your foreach as it works on arrays (or anything that is Traversable). You could fix this with the following check:
if (!empty($_POST['MAC'])) {
$my_array = $_POST['MAC'];
if (!is_array($my_array)) {
// throw some error.
}
}
Of course you would want to do this validation of your input in a more structured way by providing a validation framework which you can provide validation rules and some input and the validation framework will then handle the validation and most importantly the error messages for you.
Actually could also change the last if-statement to read:
if (!is_array($my_array) && !($my_array instanceof Traversable))
That is if you want to be sure $my_array contains something you can traverse over with foreach. The nasty bit is that the built-in array() isn't Traversable, nasty although understandable.
What's the question?
you can do str_replace(array(';',':'),'',$val);
It's usually better to trim before doing other processing on the same variable due to the overhead involved in processing data you will eventually cut
Consider using break on errors, if you halt execution on one error.
You're not really doing any updates to $my_array.
Consider doing:
foreach($my_array as &$val)
You pass by reference so all updates to $val happen to the actual array. Or:
foreach($my_array as $key=>$val){
$my_array[$key]=trim($my_array[$key]);
You can also try to create a new array for your sanitized data and then over-write your old array. It all depends on needs.
I'm also not understanding your question /problem.
But, looking at your code, you might get the feeling that in the end nothing has happened to your POSTed vars.
You're right! :-)
Your cleaned up array at the end of the script is exactly the original array.
You might want to achieve something like this: The clean array will contain cleaned values, if they consist of 12 characters.
$my_array = $_POST['MAC'];
$my_clean_array = $_POST['MAC'];
foreach ($my_array as $val) {
$val = strtoupper($val);
$val = str_replace(";","",$val);
$val = str_replace(":","",$val);
$val = trim($val);
if (strlen($val) != 12)) {
$valid = false;
$error = "Your MAC address is not 12 characters long";
}
else {
$my_clean_array[] = $val;
}
}
$mac_addresses = serialize($my_clean_array);
To check to see if you have at least one you should be able to use if(count($my_array) > 1)

Making POST values dynamic within a loop to store as an array?

I've been working on trying to write a function that will grab the POST values of any given form submission, pop them into an array, loop through the array using trim, addslashes etcetera pass that value back to a variable where it can then be passed to a database.
Now the hurdle I have atm is getting all the input,textarea,select element data into an array upon form submission. code I have follows
$fields = array($_POST['1'], $_POST['2']);
$i = 0;
foreach ($fields as $field) {
$i++;
${'field'.$i } = trim(addslashes(strip_tags($field)));
echo "POST field info #". $i ." - ". ${'field'.$i }."<br />";
}
As you can see everything is fine here baring that the POST value names are still being in-putted statically, what I need is a way to get that POST data fed into a loop which dynamically calls the POST name using an increment variable and then pop all that data into the same array. Code I have tried follows.
for ($ii=0;$ii++;) {
foreach($_POST['$ii'] as $field) {
$fields = array($field);
}
}
$i = 0;
foreach ($fields as $field) {
$i++;
${'field'.$i } = trim(addslashes(strip_tags($field)));
echo "POST field info #". $i ." - ". ${'field'.$i }."<br />";
}
Now I know this wont work but I can sense I am relatively close, so I am wondering if any clever person can help me sort the last part out? I sadly am now going to sleep and wont be viewing this post for at least 9 hours, apologies.
Thanks in advance.
Dan.
$arrayOfPostValues = $_POST; // it already is an array
$arrayOfPostValues = array_map('strip_tags', $arrayOfPostValues);
$arrayOfPostValues = array_map('trim', $arrayOfPostValues);
Or, if you really, really want to use a loop:
foreach ($arrayOfPostValues as &$value) {
$value = trim(striptags($value));
}
I'd absolutely advise against the use of addslashes, it serves very little purpose. Use mysql_real_escape_string or prepared statements instead.
I'd also advise against breaking the vales out of the array into separate variables, it can only cause problems. If you really want to do it, there's the extract function, which does exactly that. But, again, don't do it. Arrays are the perfect way to handle this kind of data.
You need to assign values to $_POST[1] and $_POST[2] to begin with, I've done this for you but normally they would be populated from a form I assume?
I'm not sure why you want to do this sort of thing: ${'field'.$key}, but I've left that part as is as I assume you must have a reason.
Anyway I've modified your code a bit, see below.
$_POST['1'] = '<h1>variable 1</h1>';
$_POST['2'] = '<h2>variable 2</h2>';
foreach($_POST as $key => $value){
${'field'.$key} = trim(addslashes(strip_tags($value)));
echo "POST field info #". $key ." = ". ${'field'.$key}."<br />";
}
The above code outputs:
POST field info #1 = variable 1
POST field info #2 = variable 2
On a side note, using field names such as '1' and '2' is not very good. Try using something more descriptive but as I said above I assume you have a reason for doing this.
UPDATE:
You can still get this to work for any form even if you are using specific names for the form elements. I have added a few lines below as an example for you.
$_POST['email'] = 'example#example.com';
$_POST['password'] = 'hgbks78db';
$_POST['name'] = '';
foreach($_POST as $key => $value){
if($value==''){
echo 'POST field "'.$key . '" is empty<br />';
/* I added the name of the field that is empty to an error array
so you have a way of storing all blank fields */
$a_error[] = $key;
}
else{
echo 'POST field "'.$key . '" is not empty<br />';
}
}

Categories