I have several input fields and I want it to submit when there is only one field with entered values and the others are empty (updating user data). I worked by now with isset() but this only sends the form when every field is filledout:
if (isset
($_POST['submit']) AND
($_POST['firstname']) AND
($_POST['lastname']) AND
($_POST['address']) AND
($_POST['ZIP']) AND
($_POST['phonenumber']) AND
($_POST['mail']) AND
($_POST['group'])
)
Later on I check in the mail template (another file) if there is a value and wheter to show it in the mail or not:
{if !empty($firstname)}{translate text='First Name'}: {$firstname|escape} {/if}
Is my idea ok or is there an easier way to solve this?
The first if statement is in conflict with your requirements; you are requiring all fields to be filled in by using the AND operation - use OR and it will work with any single field value.
Validation should/could also be performed on the page itself by using javascript as Matt recommends.
To ensure that only one field is set do the following you could count the number of entries in _POST
if(count($_POST) == 1 AND
(isset($_POST['submit']) OR
isset($_POST['firstname']) OR
isset($_POST['lastname']) OR
isset($_POST['address']) OR
isset($_POST['ZIP']) OR
isset($_POST['phonenumber']) OR
isset($_POST['mail']) OR
isset($_POST['group'])
))
Either way it's not a very elegant way of doing this - but it will work.
If you want only one value from a field which is set to required (if possible, use javascript, or HTML5 has a required attribute for that), simply ignore other values from other fields:
<?php
if ( isset( $_POST['submit'] ) ) {
$wanted_value = addslashes( strip_tags( $_POST['input_name'] ) );
// preventing from sql injection
// ignore other values
// and start manipulating it
}
?>
One suggestion would to be to use javascript and your onSubmit function on the form in addition to a serverside check. Using that, you can check all of your fields, and alert the user to fill some in BEFORE it gets submitted to the server.
In a javascript function check all of your inputs for a correct input, and allow the data to be sent to the server if it is all filled in correctly, or pop up an alert saying what else needs to be done before it can be submitted.
Doing this check strictly serverside will require a server request to check the input every time, as opposed to having the client check it, and submit it only if everything is correct.
Assuming you want to send the form if there's at least one field that's filled, you could use the following if-statement:
if(count($_POST) > 1)
This allows you to submit the form and have at least one field filled, but you can also have more fields filled.
If you want to send the form only if there's one field that's filled, you could change the above if-statement to the following:
if(count($_POST) == 2)
This allows you to have only one field filled.
The reason I use "== 2" is because the submit-button is also something that will be sent.
If you want to allow all the fields to be empty, you can use the following if-statement:
if(count($_POST) > 0)
This would allow you to submit the button and leave all the other fields empty.
The reason this works is because $_POST is a pre-defined array-variable.
To ensure that the user only uses fields that you want them to use and still keep the code clean, you can use an array.
Do the following:
$allowed_fields = array('firstname','lastname','address','ZIP','phonenumber','mail','group');
And then just add the following to your if-statement:
if(count($_POST) == 2 AND in_array($allowed_fields, $_POST))
Related
I have a form that submits to itself. When I want to edit something I take the data and place it in place of empty fields. I am trying to make a check to see if the the form has already been submitted once so that it knows that if it has come back again and put data in the blank fields on the next submit it runs an update query.
I thought what I would do is make a variable after the query is run the first time called $submitted and set that to true then when the form goes back to itself and see that true it can set another variable to $submitted_twice which will then let me run the edit query.
This approach doesn't seem to be working and I can not figure out why. Thank you for your help!
That wouldn't work because that variable is not persistent. Some alternatives to store this var across requests could be:
Use the $_SESSION global var to store the number of times your form has been submitted:
(Here I'm assuming your form uses POST as requesting method, and your submit button id is "submit")
if( $SERVER['REQUEST_METHOD'] == 'POST' && !empty( $_POST['submit'] ) ){
//
//deal with your form action here
//
//Here's the bit where you store/update your counter
if( !isset( $_SESSION['submitted'] ){
$_SESSION['submitted'] = 1;
else {
$_SESSION['submitted']++;
}
//Echo your counter
echo "This form has been submitted " . $_SESSION['submitted'] . " time(s)";
}
Use a hidden field in the form to store your counter. Check this answer hidden field in php
Hope it helps
I'm learning PHP and specifically how to secure php forms.
I'm reading an article entitled "Sanitize and Validate Data with PHP Filters" wherein the author checks if the form was submitted using the following code:
if (isset($_POST['Submit'])) {
// do something...
}
Which does work, but I've read that its best to use input filters (i.e. filter_input).
Secondly, using filter_input would also stop netbeans from nagging me about not "accessing the superglobal $_POST Array directly"
So I wrote the following:
function is_form_submit() {
$request = filter_input(INPUT_SERVER, "REQUEST_METHOD");
return $request === 'POST' ? true : false;
}
Which could be used like so:
if ( is_form_submit() ) {
// do something...
}
So my question is: doesn't my code achieve the same thing? If not, why not. Please advise.
While your code would achieve the same result in most cases, it is not the same as the isset call.
What your code does is checks if the REQUEST_METHOD is POST. That is, it checks if the user made a POST request to access the current page.
What the isset does is checks if something with the name of Submit was sent via POST. This usually happens when your submit button is <input name="Submit" type="submit" value="Submit" />, as clicking that (or hitting enter in a text field and it's the first submit button) will result in $_POST['Submit'] being set.
To see the different behaviours, compare the results of curl -X POST your-url.com/page.php with curl -F Submit=submit your-url.com/page.php.
filter_input is untouched user input.
Some scripts add/modify $_POST and $_GET directly. Fine if your code is fail-safe, but if something goes wrong with the manipulated keys/values, there could be errors.
filter_input( INPUT_POST, 'requiredID' )
Would not be affected by the type of coding below
$_POST['requiredID'] = brokenFunction( $_POST['requiredID'] );
I am using checkboxes in my form to allow the user to turn on/off certain settings. I load the form by providing the correct 'state' from values returned from the db. They can then change these and submit the form where it is processed. Example...
<input type="checkbox" name="settings[something]" '.($settings[one] == 1 ? 'value="1" checked' : 'unchecked').'/>
<input type="checkbox" name="settings[somethingelse]" '.($settings[one] == 1 ? 'value="1" checked' : 'unchecked').'/>
... and so on...
On the receiving end is where I can't seem to come up with a good solution to handle these.
If any of these are unchecked then the value is not even sent. If it is checked then a value of '1'.
So, other than doing something like :
$something = $_POST['settings'][something']
$somethingelse = $_POST['settings'][somethingelse']
... and so on
if (!$something == 1)
{
$something = null;
}
... and so on
for each value I am expecting... is there an easier way I am missing here? I have to check each value whether it was sent or not because I am also including an option to set these values as default for multiple rows in my db - not just the one they are editing.
EDIT :
I took some time to think about this. In my database I am storing these as 1 or 0 values. Rather than checking if they were posted (set) on the receiving end of the form I am going to check if they are != to 1. I can run down the list of values and everything that is not equal to 1 is set to 0. This way I have a full list of all values to update in the db AND I am verifying the data integrity before inserting it into the database (1 or 0).
I am now trying to think of a quicker way to run through my 'list' to check rather than an if statement for each. Going to play around with some arrays and see what I can come up with.
Checkboxes are a bit special as they are not sent to the server when they are not checked.
So the best way to check for a checkbox, is not by it's value, but simply by checking if it is set:
if (isset($_POST['settings']['something']))
{
// Do what you need to do
}
else
{
// The checkbox was not on the form (you should know that already) OR unchecked
}
I have a page with two forms on it (and two submit buttons), and the forms link the page back to itself with action="" for the INSERT INTO statements. One of the INSERT INTO statements is:
<?php
$sql="INSERT INTO panelProduct (length_mm, width_mm, aperture)
VALUES ('$_POST[p_length_mm]','$_POST[p_width_mm]','$_POST[p_aperture]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
One of the reasons I have put the form and the INSERT statements on the same page is that the form allows users to add products to an order, and there may be several products (so I thought the user could keep submitting until they're done...). The other reason was that I need to use a $_POST value sent from the previous page to do something else with the products they enter, and I don't know how to send it to more than one page.
Anyway, the problem I have found is that a new row is inserted into the database every time the page is refreshed, containing NULL values. This makes sense to me as the PHP will execute the statement above every time it encounters it. My question therefore is how I can make some sort of condition that will only execute the INSERT statement if the user enters something in the form and 'Submits'?
you could use the empty() method of PHP to check for null values in each of the variables.
Something like:
if(!empty($_POST['p_length_mm']) && !empty($_POST['p_width_mm']) && !empty($_POST['p_aperture']))
{
//execute your query here
}
else
{
//if there's an alternative you would like to happen if values are null, or just leave out.
}
Hope that does the trick.
You have to check if data come from your form. I'd suggest this approach - name your submit button (i.e. <input type="submit" name="my_submit_button" value="Whatever" /> and this condition to your insert code:
if( isset( $_POST['my_submit_button']) ) {
.. process your post data
}
Also, always remember not to trust user provided data. Verify if all data expected are present in$_POST and format matches requirements (i.e. you ask for number and received letters etc). If all test passed, then you are ready to commit your data to DB.
You need a condition like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) {
// a form was posted
}
Of course, you still need to check whether your post actually contains the right stuff:
isset($_POST['p_length_mm'], $_POST['p_width_mm'], $_POST['p_aperture'])
Even better is to use filter_input_array() to sanitize your incoming data; your current code is open to SQL injection attacks. Using PDO or mysqli and prepared statements is the way to go.
I have a multi-step form which asks the subscriber to check their details before proceeding with the renewal process.
What I want to do is check if the form has been modified from its pre-filled values (extracted from a Web Service) and then write it to my own local MySQL database. This should only happen if the values have been modified from the original.
I know I can do this by using the == operator but I was wondering if there was a more efficient way to do this?
You can do it with (multidimensional) arrays. Name the form/service variables carefully then compare them upon submit with array_diff which tells you which values has been modified.
Because you said this is a multi-step form, of course you can collect previously submitted values in a $_SESSION variable too.
You could do this with javascript on client side:
HTML
<input type="text" id="username">
Javascript
var input = $('#username');
if (input.defaultValue != input.value) {
//Do stuff if different
} else {
//Do stuff if equal
}