PHP post all form inputs without creating variables for each - php

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.

Related

How to create Json objects from foreach $_POST loop

i have made some random input names, because its a drag and drop page builder, so i can't guess, how much elements user will use, so i have created a random input names,
for that am using php foreach loop for $_POST requests. i have tried to make it encoded into json and then later save it into database. but it looks like something is wrong in my json.
Here are my html demo codes :
<input style="display:none;" name="DATA-BLOCK-A(some random string)">
<input style="display:none;" name="DATA-BLOCK-B(some random string)">
PS: A is for selecting element A, and B is for element B.
here is my PHP code :
if (isset($_POST)) {
//$arr = array();
foreach($_POST as $key => $value)
{
$arr = array($key => $value);
$encode = json_encode($arr);
echo $encode;
}
}
and Here is the result :
{"sortlist":"block[]=D5e3385b75a75d&block[]=K5e3385b85a75e&block[]=C5e3385b95a75f&block[]=F5e3385ba5a760"}{"save_cont_flag":"0"}{"DATA-block-D5e3385b75a75d":"0#TRANSP
<\/p>"}{"DATA-block-K5e3385b85a75e":"0#TRANSP20"}{"DATA-block-C5e3385b95a75f":"01#TRANSP0images\/250place.jpg\u00b8"}{"text-1573532276681":""}{"textarea-1573532278320":""}{"DATA-block-F5e3385ba5a760":"121212unundefined"}{"page_name":"123"}{"aff_link":""}{"pause_link":""}{"seo_title":""}{"fbook":""}{"seo_desc":""}{"seo_keywords":""}{"back_color":"#EEEEEE"}{"body_color":"#FFFFFF"}{"back_image":""}{"ty_font_color":"#000000"}{"ty_override":""}{"ty_name":"12314"}{"ty_stm":""}{"modal_para_width":"0"}{"catcha_url":""}{"catcha_un":"Yes"}{"catcha_message":""}{"code_head":""}{"code_body":""}{"modal_share_width":"0"}{"modal_cta_width":"0"}{"modal_video_width":"0"}{"modal_mp_width":"0"}{"modal_stm_width":"0"}{"modal_image_width":"0"}{"modal_bonus_width":"1"}{"ty_headline":""}{"modal_spacer_width":"0"}{"att_bar_status":"0"}{"att_delay_in":"0"}{"att_bar_color":"#bbbbbb"}{"att_gradient":"0"}{"att_text_color":"#000000"}{"att_text_font":"Open Sans:400"}{"att_text_size":"14"}{"att_bar_message":"Add Your Attention Bar Text Here"}{"att_link_color":"#000000"}{"att_link_label":"Add Link Text Here"}{"att_link_url":"http:\/\/commissiongorilla.com"}{"count_font":"Open Sans:800"}{"count_size":"55"}{"count_status":"0"}{"count_type":"0"}{"count_end":"01\/31\/2020 6:41 AM"}{"count_zone":"0.0"}{"count_eg_days":"0"}{"count_eg_hours":"0"}{"count_eg_mins":"0"}{"count_digit_color":"#bbbbbb"}{"count_label_color":"#bbbbbb"}{"count_background":"0"}{"count_language":"1"}{"count_exp":"0"}{"count_url":"http:\/\/commissiongorilla.com"}{"count_add_days":"0"}{"count_add_hours":"0"}{"count_add_mins":"0"}{"modal_countdown_width":"0"}{"modal_review_width":"0"}
and also how seperate all A BLOCKS and B BLOCKS?
Thanks.!
You don't need to use a loop.
Just used json_encode :
$json = json_encode($_POST);
If you need to get key contain DATA-block-, you can write :
foreach ($_POST as $key => $value) {
if (strpos($key, 'DATA-block-') !== false) {
// Here `DATA-block-{}`
}
}
If you change the input names to DATA-BLOCK-A[] and DATA-BLOCK-B[], $_POST['DATA-BLOCK-A'] will contain an array of all a blocks and $_POST['DATA-BLOCK-B'] will contain an array of all b blocks.
This also eliminates the need for generating random strings.

output values from array into variables in php

I have 2 pages in php. The 1st page includes a form which transimts data to the 2nd page. The form uses method=post. Data transmitted successfully in the 2nd page. I have the following code, which gets data and printing them using the code:
php?
var_dump($_POST);
foreach ($_POST as $key => $value) {
echo $value;
}
?>
All I want is to extract data from array and place them into variables, because I want to use these varaibles later in some if startments and mysql queries. Any idea how can i do this?
First, these really are basic PHP skills (or programming skills for that matter). Try to follow some tutorials or courses before attempting to write code in the "real world".
As long as you know the key for the value you want to store, this is how you do it:
$yourVariableName = $yourArray['yourKey']; // or just a number if the key is an int
You don't need for loops to do this.
EDIT
$kentroName = $_POST['kentro_name'];
$kentroSurName = $POST['kentro_surname'];
// And then the following six.
<?php
var_dump($_POST);
$array = array();
foreach ($_POST as $key => $value) {
echo $value;
$array[$key] = $value;
}
print_r($array);
?>

ow to handle possible duplicate array keys

I am trying to figure out how I can handle possible duplicate array keys.
I have this form with a select dropdown which can select multiple options (more than 1). And I am using jQuery.serialize() to serialize the form on submit.
The serialized string for a multi-select element would look like so:
select=1&select=2&select=3 // assumming I selected first 3 options.
Now in the PHP side, I have the following code to handle the "saving" part into a database.
$form_data = $_POST['form_items'];
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
$arr[$key] = $value;
}
Ok this all works for the rest of the form elements but when it comes to the select element, it only picks the last selected key/value pair. So my array now looks like this:
Array ( [select_element] => 3)
What I need, is for it to look like:
Array ( [select_element] => '1,2,3')
So I guess what I am asking is based on my code, how can I check if a key already exists and if it does, append to the $value.
If you can modify the client-side code, I would rather change the name of the select to select[], that way it will be parsed as an array in your server script.
You can't have multiple keys with the same name... They're unique keys. What it's doing is setting select = 1, then select = 2, then select = 3 and you end up with your final value of 3.
If you want to allow multiple choices in your select menu, you should change the name of the element so that it submits that data as an array, rather than multiple strings:
<select name="select[]" multiple="multiple">
which should result in something like this instead:
select[]=1&select[]=2&select[]=3
and when PHP requests that data, it will already be an array:
$data = $_POST['select'];
echo print_r($data); // Array(1, 2, 3)
PHP has its own way of encoding arrays into application/x-www-form-urlencoded strings.
PHP's deserialization of x-www-form-urlencoded is implemented by parse_str(). You can think of PHP as running these lines at the beginning of every request to populate $_GET and $_POST:
parse_str($_SERVER['QUERY_STRING'], $_GET);
parse_str(file_get_contents('php://input'), $_POST);
parse_str() creates arrays from the query string using a square-bracket syntax similar to its array syntax:
select[]=1&select[]=2&select[]=3&select[key]=value
This will be deserialized to:
array('1', '2', '3', 'key'=>'value');
Absent those square brackets, PHP will use the last value for a given key. See this question in the PHP and HTML FAQ.
If you can't control the POSTed interface (e.g., you're not able to add square-brackets to the form), you can parse the POST input yourself from php://input and either rewrite or ignore the $_POST variable.
(Note, however, that there is no workaround for multipart/form-data input, because php://input is not available in those cases. The select=1 and select=2 will be completely and irretrievably lost.)
Ok, I was able to resolve this issue by using the following code:
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
So now the loop looks like this:
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
}
This will essentially string up the value together separated by a comma which can then be exploded out into an array later.
You should change your client-side code to send the augmented value: array.join(","); and use that in your PHP side. Because when your data reaches your script, the other values have already been lost.
This should give you the solution you require
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (isset($arr[ $key ])) {
$arr[$key] = ','.$value;
} else {
$arr[$key] = $value;
}
}

How to use a foreach loop with var_export?

I have a form with some checkboxes in Drupal and I need to get the checked boxes to add them to a database. To get the values in the checkboxes I use var_export which returns an array indicating if the checkbox has been checked. After I have this array store in a variable I do this:
$checked = array();
if(is_array($data) {
foreach($data as &$value) {
if($value != 0) { //the checkbox was checked
$checked[] = $value;
}
}
However, when I print out the variable $checked there is nothing stored in it. What am I doing wrong?
The normal way to do this in Drupal would be:
$checked = array_filter($form_state['values']['name_of_checkboxes_element']);
That will give you an array of all the values selected in your checkbox element, assuming you're running this code in the submit/validate handler for the form.
Also I should mention the Devel module, it has a wonderful function called dpm() which prints the value of any variable to the messages area in a hierarchical format that you can navigate through easily.

How to access a $_POST item through the following array kind of syntax?

If i send four POST variables, but the second one — I dont know that the name="" tag will be; how can I access it? Can i use $_POST[1] or not?
Here's one solution using internal pointers:
if(count($_POST) > 1){ // just a check here.
reset($_POST); // reset the pointer regardless of its position
$second_value = next($_POST); // get the next value, aka 2nd element.
}
By the way with regards to the numeric index: PHP $_POST and $_GET are associative arrays! They do not support something like $_POST[0] or $_POST[1]. They will return NULL because they are not set. Instead $_POST["name"] would work.
From the PHP Manual: "An associative array of variables passed to the current script via the HTTP POST (or GET) method."
i have a handy function for this
function nth($ary, $n) {
$b = array_slice($ary, intval($n), 1);
return count($b) ? reset($b) : null;
}
in your case
$foo = nth($_POST, 1);
foreach( $_POST as $key => $value ){
if( is_int($key) ) //do something with $value
}
This will work if you know the other $_POST values have names in your forms (i.e., keys that aren't numbers).
You can loop through it:
foreach ($_POST as $k => $v) {
if (substr($k, 0, 3) == 'id_') {
// do stuff
}
}
But it really depends on what the criteria for the search is. In the above example it's pulling all the POST variables that start with "id_". You may be able to do it simpler if you have a different/better criteria.
You can if you convert it using array_values() first.
Example
<?php
$a = array(
"first key" => "first value",
"second key" => "second value",
);
$v = array_values($a);
echo "First value: {$v[0]}\n";
?>
Output
$ php -f a.php
First value: first value
EDIT: Thanks for commentators pointing out the initial error.
use
<?php
print_r($_POST);
?>
this will give you an idea of what is the key of the field you don't know.
Make a copy :
$vars = $_POST;
Remove the names you know :
unset( $vars[ "known variable 1" ] );
unset( $vars[ "known variable 2" ] );
All that remains is the variables you need : extract them with array_values or enumerate them with foreach, whatever.
a simple for each will do the trick if you do not know the array keys on the $_POST array
foreach($_POST as $key=>$value):
print 'key'.$key.' value'.$value
endforeach;
But it is recommended to know what your post variables are if you are planning on processing them.

Categories