I am trying to submit an html form to a php server. However, this form can have a variable length and structure (I add input nodes through dynamic javascript as the user interacts with the page, depending on his actions). How can I pick up the values contained in the form from PHP (using $_POST['xxx']) if I don't know the structure of the form?
To loop through each of the POST values, use:
foreach($_POST as $key => $value) {
echo "POST parameter $key has $value";
}
Just a fun (but valid) answer, existing answer on this question is good enough.
if I don't know the structure of the form?
Then you can simply review
print_r($_POST);
and you'll get to know the structure of what was POSTed
To find the structure of the POST OR GET OR SESSION values, you can print using
echo "<pre>"; print_r($_POST); print_r($_REQUEST); print_r($_SESSION);
You can find easily what exactly printing/structure of POST/REQUEST/SESSION.. etc
echo '<pre>';
print_r($_POST);
echo '</pre>';
Easy and clean.
Related
a newbie question!
I have set up some code to create an image with this url:
www.mywebpage.php?wc1=99&wc2=6&wc3=23
In a php page want to use the wc1, wc2 and wc3 variables from the url as inputs to a bar chart graphic
the code on the receiving webpage includes this line:
$datay=array($_REQUEST['wc1'], $_REQUEST['wc2'], $_REQUEST['wc3']);
and using the datay array I get a nice bar chart with three bars.
My problem is I want to create urls with any number of wc? variables, and then create an array with any number of bars in the resulting bar chart. The numbero f bars should be dynamically set by some other real-time process.
So I realise I need to embed this line of code:
$datay=array($_REQUEST['wc1'], $_REQUEST['wc2'], $_REQUEST['wc3']);
in a loop and add in variablles to the array one by one until they are all added (whatever number there are).
However, I am stuck at the first hurdle as I do not know how to add a variable to the array.
This code does not work:
$firstBit = $_REQUEST['wc1'];
$datay=array(firstBit, $_REQUEST['wc2'], $_REQUEST['wc3']);
You're just missing the $ from your variable name
$datay=array($firstBit, $_REQUEST['wc2'], $_REQUEST['wc3']);
foreach($_GET as $key=>$value){
echo $key;
echo "<br/>";
echo $value;
echo "<br/>";
}
You'll soon understand
In your request, pass the values thus:
www.mywebpage.php?wc[]=99&wc[]=6&wc[]=23
And then you have an array out of the box...
$myArray = $_REQUEST['wc'];
This may be asking a lot, but I am looking for a way to detect the attributes in some of my form input fields.
For example:
<input type="text" name="fieldone" id="fieldone" value="me#me.com" />
I can simply use a php foreach loop to get the key => value information.
<?php
$querystring = "";
if ($_POST){ $kv = array();
foreach ($_POST as $key => $value){ $querystring .= "$key=$value<br>"; }
}
?>
And this helps with mediocre debugging reasons.
However, this only detects the name and value of the form field. How do I detect the "id" attribute, or any custom attributes I may add.
Is there a way to detect/display the attributes of POST variables? Or does php stop at the name/value?
Only Name and value are senet to the server. ID and other attributes are not sent at all (why would they).
BTW: You'll want to use print_r($_POST); or var_dump($_POST); instead of your loop.
Nothing except the name and value are sent over HTTP.
You'll need to use some JavaScript pre-processing for that.
For example, on form submit, you could use JavaScript to store all the attributes with the name, but this will be messy.
When a form is submitted, only the name and value fields are used. The other fields are only used client side (inside the browser) and not returned to the server.
I have a survey script that has 3 questions per page. When users answer the questions on the first page and click next, the data from the previous page is stored in $_SESSION['survey']['data'] by doing this:
$data = postToArray($_POST, $ignore_fields);
$_SESSION['survey']['data'] = $data;
$data is an array that looks like:
array('question' => 'answer', 'question' => 'answer');
postToArray does a few checks and manipulates the actual submission a bit, before returning it to $data.
When the user is on page two of the survey, the same thing happens over. I assumed that when $data gets added to the session, via $_SESSION['survey']['data'] = $data;, that it would append to the session array if the 'question' (key) did not exist, but if it did (because the user went to a previous page and changed their answer), that the existing value with the same key would be overwritten, however the last page's submission overwrites everything in the ['data'] array in the session. Come to think about it, that makes perfectly sense.
I tried various things, such as retrieving the $_SESSION['survey']['data'], storing it in array, reading the last submission, merging the arrays, and then re-saving everything in the SESSION, but my code didn't work out -- does this approach make sense? Is that possible?
I also tried array_push, but no luck there.
In addition, I tried adding to $_SESSION['survey']['data'][], which at least saves everything (each submission in its own array), but then if the user goes back a page, any values they change and re-submit are added as another array.
Preferably, I'd like one giant array with all questions/answers and it keeps adding to that array and overwrites any values with existing keys.
What's the best approach?
Thanks,
-Ryan
SOLUTION IMPLEMENTED
$data = postToArray($_POST, $ignore_fields);
foreach($data as $question => $answer)
{
$_SESSION['survey']['data'][$question] = $answer;
}
Try to serialize the data before saving it in a session variable.
http://php.net/manual/en/function.serialize.php
Loop through the $data array and set it up as naiquevin stated, $_SESSION['survey']['data'][$data['question']] = $data['answer'].
<?php
session_start();
if(!isset($_POST["submit"])){
$_SESSION["abc"]=array("C", "C++","JAVA","C#","PHP");
}
if(isset($_POST["submit"])){
$aa=$_POST['text1'];
array_push( $_SESSION["abc"],$aa);
echo "hello";
foreach( $_SESSION["abc"] as $key=>$val)
{
echo $val;
}
}
?>
Just wondering If there is a quick code/ short cut to get all textbox, combobox and radio button values in the current html page using php. Instead of $_Get and give names for each.
I have 4 pages in my application, where a user can go back and forth, I want to retain all values the user inputted in my page, some of the controls are static and rest are dynamically created. I just want a generic way of retaining all input boxes with values, instead of specifying names for each
You can enumerate them all using a foreach loop as such:
foreach($_GET as $name => $value) {
echo "<b>", $name, ":</b> ", $value;
}
I don't see the usefulness of doing that. Without field names, there is no way of distinguishing between multiple input areas. Maybe provide an example of exactly what you are trying to achieve?
If you're using GET to transfer form data, then you just need to make sure you pass all those parameters in the URL string to the next page. You could use foreach to construct the query string as such:
$returnStr = "";
foreach($_GET as $name => $value) {
if ($name = ((array_keys($_GET)[0]))
$returnStr .= sprintf("?%s=%s", $name, $value);
else
$returnStr .= sprintf("&%s=%s", $name, $value);
}
// now $returnStr is of the form "?key1=value1&key2=value2"...
Then, in your form that you are using to submit data, append $returnStr to the action attribute:
...
<form method="get" action="page2.php<?php echo $returnStr; ?>">
...
This should append any extra data fields you create to the get request. Keep in mind this would be harder to do with post... although post is a bit more secure since your values aren't just sitting in the URL bar.
I haven't actually tested this since I don't have a PHP-enable server here, but it should work..
The question is not very clear, however if you simply want to display all of the form field names and values, the easiest way is:
echo '<pre>' . print_r($_GET, 1) . '</pre>';
The print_r function is very useful when working with forms with a lot of fields.
Hey, I'm programming a feedback form on a website for a client, however, there are over 100 inputs (all uniquely named). I was wondering if there was a loop I could run to get all of the variables, do you have to call them like this:
$variable = $_REQUEST['variable'];
EDIT:
I'm going with $_POST as recommended by everyone here - thanks for the input! I'll just manually go through and write a line for each $_POST I have.
You can loop over all veriables in the $_PREQUEST array:
foreach($_REQUEST as $key=>$value){
//doStuff
}
However this will include all send parameters, not only the input. Also you should not use $_REQUEST but $_POST or $_GET
If you don't want to have hundreds of uniquely named variables and want to have arrays of data turn up client side, there is a handy form trick you may want to try.
<form>
<input name="foo[a]" type="text" />
<input name="foo[b]" type="text" />
<input name="bar[]" type="text" />
<input name="bar[]" type="text" />
Client Side:
<?php
$_POST['foo']['a'];
$_POST['foo']['b'];
$_POST['bar'][0];
$_POST['bar'][1];
?>
echo "<pre>";
print_r($_POST); // or $_GET
echo "</pre>";
If you are dealing with items that you possibly won't know the name of but need the values then you are dealing with a much larger problem than you think.
But the above snippet should show you all variables set and their values when you submit the form
I think you should start out with a list of all variables that you expect, and loop only over those. If you don't, hackers can inject any variable name... In fact, you're reemplementing the old, terribly bad idea of Register Globals. So, don't do that...
In fact, why not keep the input in an associative array, just like $_POST? You might still want to remove those values that you didn't expect.
As in my comment above, don't use REQUEST, use POST. I'd probably write a line for each one so that I was aware of what was happening. You don't want people to post extra variables that still get parsed.
You can write simple code to algorithmically obtain all inputs from a posted form, but this is a dangerous business, one that is ripe for exploitation.
The $_GET and $_POST array variables contain every parameter passed via URL or POST method respectively. You should rather use that variables instead of extracting every item like the register_globals option or extract function does. See Using Register Globals for the reasons.
I can't add a comment on Pim Jager's post, but here's an example code:
foreach($_POST as $key=>$value) {
echo($key.' > '.$value.'<br />');
}
Use an array with the fields you want copied from POST and store the data in an array. It's a lot easier to maintain.
$fields = array("name","email","addr","bla","bla2");
$form = array();
foreach($fields as $field){
$form[$field] = $_POST[$field];
}
Now you've got all the data inside $form.
You could also make a similar thing when creating the form. (Although it's trickier..)
Cheers!
foreach($_POST as $key=>$value) {
${$key} = $value;
}
but this does the same thing as extract()