Lets say I have something like this:
http://gyazo.com/642987562175afc6d11a962762327744.png?1329570534
Basically, the user fills out this form, and if there are more people, pressing tab on the last form will add another input. I believe Quizlet does something similar.
How would I parse all these inputs with PHP? I obviously don't know how many inputs there will be.
Cheers
Just create every (similar) element of the form (in html) as an entry of an array (in php). See http://php.net/faq.html.php#faq.html.arrays
You can just iterate over the elements then
foreach ($_POST['MyArray'] as $element) { echo $element; }
Just to make it complete: If you click on the link above then you see, how your form elements should look like.
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Make sure each input has a unique name by incrementing it for each additional field, eg:
<input type="text" name="field-1" />
<input type="text" name="field-2" />
<input type="text" name="field-3" />
Then when you submit it to your php script you have access to all form fields in the $_GET or $_POST arrays, depending on your form submission method.
You can do a simple while loop to iterate over $_GET['field-1'], $_GET['field-2'], $_GET['field-n'].
Make sense?
Variable-length argument lists
PHP has support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions.
No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal.
http://php.net/manual/en/functions.arguments.php :)
Related
I have a form that contains html entities in an input field, something like:
<input type="hidden" name="foo" value="<?php htmlspecialchars($foo) ?>" />
If $foo takes in the value of something like "<b>foo</b>", it seems that when the form is posted to the PHP script, the value of $_POST['foo'] is already decoded...so does that mean I don't need to use htmlspecialchars_decode to convert $_POST['foo'] back to its original form $foo?
Thanks for any inputs on this issue.
When it comes to user input, code very defensively. Never make any assumptions. While the initial state may be set by the server, there's nothing stopping someone from manipulating the value of your hidden input to a malicious value. At that point it's on you to handle that value responsibly, so make sure you cover any case that is possible.
i've just noticed that if i have a lots of input fields with unique names on my form, sometimes the data does not get passed to the php page that is processing it. however, if instead of naming each field like this:
<input type="text" name="userid-1121" value="1">
<input type="text" name="userid-1122" value="1">
if i build the names into an array like this:
<input type="text" name="userid[1121]" value="1">
<input type="text" name="userid[1122]" value="1">
the array method doesnt seem to loose any posted data.
Just wondering if this is normal and if my solution of using the array method is better?
thanks
If you have a lot of input with different names, every input is part of the superglobal variables $_GET or $_POST and it's affected by the directive: max_input_vars, so your solution of using an array is valid because you are limiting the number of different variables. Other solution is to increase the value of this directive in your php.ini
There is no better way, just easier.
If you use the array method, it will be more easier to read / pass the data later on.
Apart from that, they are both the same.
Okay so my title might be a little confusing, but let me explain my situation:
I have a pretty big form with lots of fields, some which are required, some which are not. I do validation with JS, but then I'm also doing validation on the server side with PHP.
One of the things I'm asking the user for is a "Header Name". Now, header name has the name attribute of "header1". The user has the option of adding more header fields on the form. So if they click a button it adds another "Header Name X" with name attribute "headerx".
Got it? Now, the problem is, in general these header fields are not required, but I do have the condition that they MUST supply at least one Header field. So they could supply 100, they could supply 2, they might supply 1, but if they don't supply any then validation should fail.
I can't think of a good way of checking for this in PHP though. I know your fist thought is just check if $_POST contains anything. Won't work though because they are multiple other fields in this form that are required that have nothing to do with these Headers. So I can't just simply check to see if $_POST contains something because it always will.
Is there a way I can like combine isset() with a regular expression? Like isset($_POST['header{\d+}']. Which would be saying like header with atleast one digit following it.
Thanks for the help!
EDIT: Oh and if this wasn't hard enough already, the amount of Header Fields is limitless. So I can't just loop through all the possible "headerx" because that would obviously be an infinite loop.
You could have field names with []:
<input type="text" name="foo[]" value="x" />
<input type="text" name="foo[]" value="y" />
Then $_POST would be like:
array('foo' => array('x', 'y'));
You could even have associative arrays:
<input type="text" name="foo[bar][first]" value="x" />
<input type="text" name="foo[bar][second]" value="y" />
Would look like:
array('foo' => array('bar' => array('first' => 'x', 'second' => 'y')))
You can loop through the elements like this:
$i = 1;
while($row = $_POST['header' . $i++]){
//do stuff
}
this will keep going until there are no more sequential elements.
Why not simply look at it this way: In your JS on the other end, when you are doing validation, have the last check a check to verify that a header is sent - and it it passes, set a hidden field in the form to a true value - then in your PHP you can check that particular element without having to worry about every possible header that is sent.
if(!count(preg_grep('#^header\d+$#',array_keys($_POST))))
{
//no header submitted
}
This will allow to use a RegExp as requested, but I also would prefer the solution by jpic
If i have 3 checkboxes that you can check for the transport available: Taxi, Train, Bus.. how should i pass them in a nice way? Cant you like pass a array with Transport = bus, train (those you checked), or maybe you have to send them seperatly one variable at a time, because it is inside a form (and already are a array all of it)?
I assume you are talking about sending the data from the client to the server. If so, you can give the checkboxes the same name:
<input type="checkbox" name="transport[]" value="Taxi"> Taxi <br />
<input type="checkbox" name="transport[]" value="Train"> Train <br />
<input type="checkbox" name="transport[]" value="Bus"> Bus <br />
When you sent the form, the data will be available as array in $_POST['transport'] (or $_GET, depending on which methods you use). The [] in the input field name will make PHP parse the data as array.
More information in Variables From External Sources.
Some more explanation:
Without the brackets (i.e. []), the resulting query string would look like this (assuming Taxi and Train are selected):
transport=Taxi&transport=Train
PHP, in contrast to other languages, will only consider the last value for the same key. In order to make PHP treat values with the same key as array, you have to append [] to the name.
All input fields will be passed as part of your $_POST or $_GET arrays, based on the method type of your form submission. Checkboxes are passed as name=on or name= whether the checkboxes are selected or not. Depending on how you're processing the submitted form data there are different ways to work with the values. I hope this helps?
If you use something like this:
<input type="checkbox" name="transport[]" value="bus" />
<input type="checkbox" name="transport[]" value="train" />
<input type="checkbox" name="transport[]" value="taxi" />
The values will be passed as an array accessible with $_POST['transport']. If the user checks the first and the last checkboxes $_POST['transport'] will contain two strings: 0 => "bus", 1 => "taxi".
Also see http://jetlogs.org/2007/07/19/passing-input-arrays-in-php/.
The form that will be submitting the data will have somewhere between 10 and 100 values being sent to the PHP file. The number of inputs is stored in a variable called count within my javascript function but I don't know how to transfer its value to my PHP file.
Another idea I had was to have a while loop that detected a null value and to have a counter within the while loop to keep count.
How should I handle this?
No need to submit the count. You can just submit your dynamic number of values as an array. You can use the PHP array notation in your name attributes:
Input 1: <input type="text" name="myvar[]" />
Input 2: <input type="text" name="myvar[]" />
...
Input n: <input type="text" name="myvar[]" />
On the PHP side, $_REQUEST['myvar'] will be an array.
Without knowing more about your implementation, I would suggest the latter of your two options: use PHP to loop through your $_POST array and count the valid values you have. This is the best option as it is more secure and reliable.
I think there might be a more "correct" way to do this, but what I would do (without knowledge of a better way) is have a hidden form element something like
<input id="hidden_count" type="hidden" name="count" value="" />
And then have a function called onsubmit that sets this value and returns true to tell the form to continue
(with jQuery)
function onSubmitFunc(){
$('#hidden_count').val(count);
return true;
}
I'm sure there's a more elegant solution, but that should work for what you need.
If you have access to Javascript, the easiest by far would be to turn your data into JSON on the client side, send it to the server as a single string variable, and use json_decode on the server to get the properly formatted value back. You can react to the submit event on your form to have the Javascript compute the JSON before the data is sent.
Otherwise, you can have the Javascript output the number of fields to a specific hidden variable within your form. The server can then read that value, and look for the data by key in its input.
I guess you use javascript for creating the additional input element, if you just name ascending, you could use count to loop through the $_POST data. Or else use a hidden element form for counting the new input elements and post it, that way you have the correct number, and know how long you should be count.
Maybe I am not getting this, but if count in your JS file corresponds to the number of input elements in the form which is send to your PHP file, why not count() them on the serverside. The data will be in the $_POST array.