Let's suppose I have the following PHP code which attempts to read from an array called $arr which takes on the values {fullname, studentnumber, email}. Upon submission of my HTML form, this PHP code will execute the foreach loop, and store the values posted to the page in the $_SESSION array.
foreach($arr as $field):
$_SESSION[$field] = $_POST[$field];
endforeach;
The above code doesn't work as intended. If I were to replace the above code block with the code below, the values in the fields on my page get stored correctly in the $_SESSION array.
$_SESSION[fullname] = $_POST[fullname];
$_SESSION[studentnumber] = $_POST[studentnumber];
$_SESSION[email] = $_POST[email];
How do I accomplish this, in an efficient and expandable way? I don't want to have to write new $_SESSION statements every time I add a new field to my form.
EDIT: // The first block of code actually works as intended. There was a typo originally!
what you want is to use array_keys() otherwise you're getting the array contents.
foreach (array_keys($arr) as $field)
Let me know if this works/is what you're looking for :)
Related
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.
I am having trouble figuring out how to correct an issue I am having with the following code. I am trying to list the names and emails of all the people in my Active Directory. This code works. However, I also get the following warning when it is executed.
Warning: Cannot use a scalar value as an array.
From what I have read online I need to set " $name['mail']['0'] = "Not Found";" to an array. My question is how would I go about doing this. I have tried every way I could think of with no success. If anyone could provide me with some feedback it would be greatly appreciated.
foreach ($results as $name) {
if (!isset($name['mail']['0'])){
$name['mail']['0'] = "Not Found";
}
$allnames[$name['cn']['0']]['mail'] = $name['mail']['0'];
It looks like you are trying to assign the "Not Found" value BACK into the results of the ldap query you are running.
When I wrote code to get user information from ldap, I always inserted values into a different array (getting the fields I wanted) and then displayed THAT array out in the HTML:
foreach ($results as $name)
{
if (isset($name['mail']['0']))
// Check if it IS set, rather than not set and then append the data.
{
$allnames[$name['cn']['0']]['mail'] = $name['mail']['0'];
}
}
Then after you have all the fields you want you display the $allnames array.
Having said that, when I construct the array of user information, I make the array much much simpler - knowing what I want to display out, more along the lines of this:
foreach ($results as $name)
{
if (isset($name['mail']['0']))
// Check if it IS set, rather than not set and then append the data.
{
$allnames['mail'] = $name['mail']['0'];
}
}
You (or at least I) don't need to follow the ldap structure when making the array of information I have gathered, but rather I want to get specific fields from the directory and then display them by what they are - for example when I output the value in mail I might want to hyperlink it as an email address, so I keep it in an array element that I know by key and refer to later.
I have some checkboxes in my app, which could be checked (naturally). This checkboxes are named like 'checkboxname[]', and every checkbox has it's own value (4,5,6,7,8, and so on).
Now I would like to get all the values (just from the checked checkboxes!!) into an array, send this array over ft.upload, and split the array with foreach with php. But my php file is always saying that the arguments are invalid for my foreach function.
Heres the javascript.
var values = new Array();
$("input[name='checkboxname[]']:checked").each(function(){values.push($(this).val());});
params.checkboxname = values;
Heres the php code.
$rubriks = $_POST['checkboxname'];
foreach($rubriks as $ausgabe){
echo $ausgabe; }
I don't know whats wrong. I tested with var_dump whats actually send from the javascript, an theres no checkbox-array so I think there is the problem?!
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;
}
}
?>
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()