Secure html form variable - javascript

I don't want my users to be able to change the ('+res.id+') and ('+res.level') using inspect element because if they do it changes the outcome of the submit button.
For example '+res.id+' is = 2 and 2 is equal to a firedragon, but if the person uses inspect element they can change that 2 to a 1 and 1 is equal to a lightningdragon. Then when they click battle the firedragon was changed to a lightningdragon. Basically they can battle whoever/whatever they want.
Is there anyway way to prevent people from changing those variables OR check if the variable was changed so I can send the user an error message?
html += '<form name="input" action="ingame.php?page=attack/travel/startbattle" enctype="multipart/form-data" method="post">';
html += '<input type="hidden" id="goid" name="goid" value="'+res.id+'">';
html += '<input type="hidden" id="level" name="level" value="'+res.level+'">';
html += ' <input type="submit" value="Battle!" class="button"/>';
html += '</form>';

If you want to store variables you can trust then don't send them to the client, instead keep them only in server memory (using Session state, a database, or some other backing-store that persists between requests).
If you need to share values with the client, then send them out but don't accept them as input from the user.
As a third option, if you have a completely stateless server and need to expose values to the client, then you can encrypt and/or sign the values, so that when they're returned from the client you can verify that they haven't been tampered with. Using Message Authentication Codes is one such implementation of this approach: http://en.wikipedia.org/wiki/Message_authentication_code

You can’t stop a user from submitting whatever parameters they like to your form endpoint. Even if you could somehow stop the form values from being changed, someone could use curl or the like to send a custom-crafted request to the server.
You need server-side validation of input values. You may need to store an intermediary object that can be retrieved when the form is submitted, then you won’t have to carry along those values as hidden fields.

Related

Is there a way to take user input from a form and append it to code I already have?

I have html and css code for a basic quiz template. I want to give the user the ability to make their own custom quiz.
Example: I have created my own math quizzes, science quizzes, etc, that the user can take. I am looking for the ability that Users can make their own personal quiz.
You don't append users input to your code. You should have your quiz as a data and let the user update the data by adding their quiz.
The structure of a form looks like this:
<form method = 'post' action='./handleSubmission/'>
<label>Question 1: </label>
<input type='text' class='question' name='question1'>
<label>Answer 1: </label>
<input type='text' class='answer' name='answer2'>
<label>Question 2: </label>
<input type='text' class='question' name='question2'>
<label>Answer 2: </label>
<input type='text' class='answer' name='answer2'>
<button>Submit</button>
</form>
(You can find all the different input types here. You might want another type for multiple choice questions.
When the user clicks on submit, the default behaviour is that the content of the form will be sent as an http request to the action url. if you set post as method, the method will be POST. If you set get as method, the method will be GET.
Now, in order to do something useful with it, there needs to be a server-side script at './handleSubmission/' or whatever url you put in here, that can read the sent data and upload it to some place where you store the data for your quizzes. This can be either a database or a repository containing some files.
I'd go for json files. Because json files can very easily be decoded and used in any web scripting language.
In PHP for example you'd get the content of the form through a special array called $_GET (or $_POST depending on the method).
You'd then have access to 'question1' with $_GET['question1'].
You'd then have to find a way to put that data into a json file.
To use the content of the json files, you can either use a backend script or a frontend script like javascript.
Are you already using a scripting language for the backend such as PHP or Python? Or do you focus on frontend?
If you want to focus on javascript and frontend, this is the alternative:
<form>
//...
<button id='btn-submit'>Submit</button>
</form>
As you can see, i ommited action and method because in this alternative we don't want to send the form to the server. What we'll do is, when the button is clicked, we'll capture the content of the form without refreshing the page, and then send it a Backend-as-a-service like Google Firebase.
const submitButton = document.querySelector('#btn-submit');
submitButton.addEventListener('click', (e) => {
/* important! prevents the default behaviour which is to submit the form */
e.preventDefault();
const data = [];
/* do stuff here to retrieve the data from form like: */
const questionInputs = document.querySelector('.question');
const answerInputs = document.querySelector('.answer');
for(let key in questionInputs){
data[key] = {
question: questionInputs[key].value;
answer: answerInputs[key].value;
}
}
sendToFirebase(data);
});
You'd then have to write the sendToFirebase function.
Firebase requires making an account, starting a project by giving a name etc. Then it gives you the code to put in your app and you can read the documentation about how to upload data to the Realtime Database.
I strongly prefer the first option however. Because i think in this case the Firebase Realtime Database would be a bit cumbersome to use compared to just setting up a small backend script that generates json files.

How to process many form inputs with PHP

I am building a admin panel for a distribution company and they requested to have a page where they can add orders for all clients , so i generated a form which dynamically adds inputs for each product within the system and and for each client a row is created (see )
|The problem is , every product/client that is added, will add more and more inputs, i already had to increase max_input_vars, but this can easily reach to thousands , if not tens of thousands of inputs which will slow down the application dramatically , my question is, what is the best approach to process all these inputs, or another approach to achieve this functionality ?
I would either reconsider to add an maximum to the amount of input fields which are added per client or create a seperate page for each client on which the input fields are generated.
If you do want to continue you might want to consider extending the max_execution_time which defaults to 30 seconds, by adding ini_set('maximum_execution_time', '60'); to the top of your script.
To process all those rows on the server side. Make your input fields arrays which hold the client name as a key: <input type="text" name="your_value[client1][column1]" /> and for your next client do <input type="text" name="your_value[client2][column1]" /> increment the column for each column.
Then on the server side your can perform a foreach loop to get the values.
foreach($_POST[your_value] as $client)
{
foreach($client as $key => $val)
{
echo $val;
}
}
Use JavaScript (or something client side) to only submit the data that has changed.
If the chart is filled with stored data (in a DB I assume) than when an entry is changed you can use an AJAX request to your php script so it saves the changed data to the DB.

How do I sync an AJAX call to a php file with posting data through a form to the same file?

My problem is update.php only gets the posted form data (post_edit). The variables posted earlier through AJAX don't go through
Notice: Undefined index: id_to_edit in ...\update.php on line 5
Notice: Undefined index: column_to_edit in ...\update.php on line 6
What I'm trying to do:
I have a callback function that traces the mouse's position on the table's body. This is done to detect the column and the id of the cell that the user wants to edit - id integer and column string are posted to a php file through AJAX and used in an SQL query using both values (for coordinates) on top of the data the user wants to update (posted through a form, more on this later).
Editing is done this way: when a user mouses over a cell a form is created inside, and filling in that form should post the data to update the corresponding entry in the SQL table (which is found by using the coordinates from the callback function). Mousing out removes the form.
To paraphrase a bit
How do I post the coordinates and the form data to a php file so that all these values can be used in an SQL query? If what I've been doing is fundamentally broken, is there another way?
$(function(){
$("td")
.hoverIntent(
function(e){
var id_of_edit = $(e.target).siblings('th').text();
var $clicked_column_i = $(e.target).index() + 1;
var column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();
$.ajax({
type: 'POST',
dataType: 'text',
url: 'update.php',
data: {
'id_of_edit': id_of_edit,
'column_of_edit': column_of_edit
},
});
var $edit_button = $('<form action="update.php" method="post"><input type="text" name="post_edit"/></form>');
$(e.target).append($edit_button);
console.log(e.target.innerText + " was clicked");
console.log(id_of_edit + " is the ID");
console.log(column_of_edit + " is the column name");
//just to check the tracer function is working correctly
},
function(e){
$id_of_edit = $(e.target).siblings('th').text();
$clicked_column_i = $(e.target).index() + 1;
$column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();
$(e.target).children('form').remove();
});
});
update.php:
<?php
include 'config.php';
echo $_POST['id_to_edit'];
echo $_POST['column_to_edit'];
echo $_POST['post_edit'];
$stmt = $pdo->prepare('UPDATE food SET :column = :edit WHERE id = :id');
$stmt->execute([
'id' => $_POST['id_to_edit'],
'column' => $_POST['column_to_edit'],
'edit' => $_POST['post_edit']
]);
?>
An ajax request and a form submission via standard postback are two separate HTTP requests. Your "update.php" script will execute twice - once for each separate request, and each request will have separate sets of POST variables, according to what you sent on that request. The variables do not persist between requests - just because you sent them to the same endpoint script does not matter.
To summarise: HTTP requests are stateless - they exist in isolation and any given request knows nothing about previous or future requests. Each one causes the named PHP script to run from start to finish, as if it had never run before, and might never run again. It remembers nothing about the past, and knows nothing about the future, unless you do something about it explicitly.
If you want values to persist between requests you have to store them yourself - in a DB, Session, cookies, whatever (it's up to you) - and then retrieve them later when you need them.
Having said that, looking at your server code it's not clear why you would want two separate requests anyway - you are doing a single UPDATE statement in the SQL, so it would make more sense to use one HTTP request to transmit all the data to the server, and then execute the script which runs the UPDATE. Unless there's some reason in the UI why this can't be done, in which case then you need to persist the values somewhere in between requests. From your description, you could potentially capture the cell/column ID into a hidden field inside the form you generate, rather than sending them immediately to the server via ajax. The hidden field values would then be posted to the server together with the user-generated values when the main form is submitted.
Also, if you really are using the mouse's position to determine the cell, this sounds very unreliable - browser windows can be resized to anything. Surely putting an ID inside the HTML markup of the cell (e.g. as a data- attribute) which you can then read when the cell is clicked / moused-over would be much more reliable?

JQuery Fetch data from MySQL and store into Variable

I am continuing to work on my multi stage bootstrap form, and I have hit a roadblock trying to pull info from my DB.
The main page is PHP and is named quote_tool.php
I have the following functional requirements:
The data must come from the MySQL database.
The user should only receive data that they requested (i.e. a row from the db with info about user license should only be grabbed if the user checked a radio button to include user licenses on the form).
The information needs to be called from the DB without refreshing/reloading the page.
Currently I have a table in my DB with the following columns:
There are 3 different products in that table right now. The user can select a radio to say they want to include endpoints, and then there are 3 check boxes to allow the user to input a quantity for which endpoint(s) they want to include.
The input field looks like this:
<label for="device-9102" class="form-partner-label"><input type="checkbox" class="quote-chkbox" id="9102-chk"> 9102 IP Phone</label>
<input type="text" name="9102-quantity" class="form-endpoint-qty form-control" id="form-partner-9102" readonly value="0">
When the user checks the box and input a value this value is dynamically updated on the summary page as well in the following field:
<input type="text" readonly name="sum-9102-qty" class="summary-field sum-qty" id="sum-9102-qty">
There is also 2 other fields on the summary page regarding this product.
MSRP
Part Number
MSRP is a hidden field that will be used for additional calculations, but Part Number is visible on the summary page.
When the user inputs the value for the endpoint quantity I need to call the DB and pull the MSRP and Part Number from the refEndpoints table.
I am currently building a function to call the DB when the user hits the "Next" button on the form, and that looks like this:
//Call DB to fetch part number and msrp of 9102
$('#form-partner-9102').change(function()){
var quantity_9102 = $('#form-partner-9102').val();
if(quantity_9102 !== 0) {
}
});
This is the point that I am stuck at. I am not sure how to call the DB and place the values of the part number and the MSRP in the correct input fields on the summary page.
jQuery runs on the client side so it cannot connect to MySQL directly, however your question is tagged php, which runs on the server side and thus can connect to your database. First you will need to setup a PHP file that can respond to HTTP POST requests and return JSON. Here is a great answer that shows you how to do this: Returning JSON from PHP to JavaScript?
Once set up (and you will need to workout what parameters this PHP file takes in and how it converts this into a query so that it can respond) you can now setup some simple JavaScript to call this PHP file (lets call it query.php). Code that does this might look like this:
$.post('/query.php', {quantity: $('#form-partner-9102').val()}, function(resp) {
$('#PartNumber').html(resp.PartNumber);
});
Some important things to keep in mind are to always be sure to use prepared statements when taking user input and turning it into a query (don't just build a SELECT statement by joining strings). Also be sure to look at your event binding, you can probably write one generic handler for your inputs that takes the partner ID as a data-* attribute making your code smaller and easier to maintain.

How to validate username using Javascript?

I want to know how can I validate using Javascript that if user has entered any username at the time of creating an account is already present in database and ask user to type any other username?
Attach listener for blur event for <input /> element.
Using AJAX send request to the server (with field value as parameter)
On the server side check whether given username is already in use or not
Based on server's response display (or not) This username is already in use message
jQuery (I'm too lazy for pure JS) + PHP sample code:
<form ...>
...
<input type="text" name="username" id="input-username" />
<p class="error"></p>
...
$("#input-username").blur(function() {
$.post("/check-username.php", { username: $(this).val() }, function(data) {
if ("0" == data) { /* username in use */
$(this).next("p").text("This username is already in use.</p>");
} else { /* username is fine */
$(this).next("p").empty();
}
});
});
<?php
$username = $_POST['username'];
// check whether given username exists in database
$usernameExists = ...;
echo $usernameExists ? '0' : '1'; // 0 if exists, 1 if not.
The answer is AJAX. If you must validate against a database, you need to make a call to the server. The only way to do that (EDIT: properly) without reloading the page is AJAX. How you implement it will depend upon what javascript libraries you are using, if any, and what your server is like. I suggest you do a little searching and reading on it - this is a pretty common use case.
Personally, I would use a JQuery validation plugin just to make things simple.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
But in general it would consist of a small AJAX request to a server (ie. JSON object) with the username and do a 'search' in your database and return either true/false after the user hits enter or tab in the textfield (attach an event listener). Then within your callback response alter the DOM elements of your choice to indicate to your users whether the account name is already present in the database or not.
Ajax might not be the only solution, since usernames are generally public. A simple way is to just have an RDF/XML document at some point (which just updates with every new user added) which has a list of all the users on your site that you can easily just traverse with Javascript DOM to see if that user is already in use. You also make them pay computational power, not you, depending on how nice you are it's an advantage or a dis-advantage.

Categories