How to protect HTML form from blank submission - javascript

Basically I'm using this tutorial: HTML FORM
Everything is working as it should but one flow I've found is that everyone can see the URL for your .php which in this case is "url: "contact_mail.php""
Is there a way to protect my form from blank submission when someone type the url and just press enter.
Example: www.mywebsite.com/contact_mail.php
Thank you!

First you can use the required attribute on mandatory fields for client-side:
<input type="text" name="mandatory_field" required>
But you will need to verify server-side in case the user modified the form. You can use empty() on any variable ($_POST or $_GET):
if (empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
You can use isset() to verify if a field is submitted. Your validation could be:
if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
Other cases:
If all fields are mandatory you could check with in_array():
if (in_array(false, $_POST)) {
// print error message or redirect to form page
}
If doing various data validation here is what I use to do with forms:
$errors = [
'empty field' => empty($_POST['field']),
'another error message' => $another_condition
];
if (in_array(true, $errors)) {
$error_message = array_search(true, $errors);
// print or redirect, and you can tell the user what is wrong
}

Say you have the following form;
<form action="savething.php" method="GET" name="mythingform">
<input name="thing1" type="text" />
<input name="thing2" type="text" />
<input type="button" value="Submit" onclick="validateAndSubmit()" />
</form>
In this, instead of a submit type input, I have used a button. This means, something needs to happen before the page will submit, so, for example;
<script>
function validateAndSubmit()
{
var thing1 = document.getElementsByName("thing1")[0];
var thing2 = document.getElementsByName("thing2")[0];
if (thing1.value.length > 0 && thing2.value.length > 0)
{
document.forms["mythingform"].submit();
}
}
</script>
The JavaScript function here will only call the submit on the form when the inputs are not empty
In terms of stopping someone from accessing this without permission;
<?php
if (!isset($_REQUEST['myvariable'] || empty($_REQUEST['myvariable']))
die("Please make sure the form has been submitted properly with all required information");
Using die in this, will terminate execution of the script any further, you can also use exit and both allow you have have a "termination message" attached to them as part of the stoppage process
$_REQUEST isn't the safest of options, but it permits you to use GET or POST methods from forms to be able to retrieve and use data

Form blank submission you can use java-script validation or jquery validation validation or you can also use php validation to avoid blank form submission.
core js validation
simple example:
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
jquery validation
validation library
https://jqueryvalidation.org/documentation/
example:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
I hope it helps.

(1) there should be no danger from someone 'just entering' the URL in their browser - the back-end code is supposed to respond only to POST, not to GET (entering a URL in a browser makes it issue a GET request for the given URL).
(2) the quoted example code already includes client-side validation (including checks for empty fields), so if someone legitimately uses your entry form, they will not be able to send a blank form.
(3) all that remains is to protect the back-end code from accidental or malicious posting of empty forms (and any other use that is undesirable). The example PHP code doesn't have any checks, you should add some - like the isset(...) or empty() checks suggested in another answer here).

Use if (empty($_POST['your_field']))
So if a post or get query reaches your php script, empty will check if the field is empty or not.
So something like this:
if (empty($_POST['your_field'])) {
echo 'Field xxx should not be empty';
}
Although isset would be better, since if they just go to the link, your POST and GET variables are empty.
So something like this is kinda foolproof:
if (!isset($_POST['your_field']) || empty($_POST['your_field'])) {
echo 'Field xxx should not be empty';
}
Didn't think i'd need a separate piece of code for GET, but ok.
if (!isset($_GET['your_field']) || empty($_GET['your_field'])) {
echo 'Field xxx should not be empty';
}

Related

How to access PHP variables after posting and redirecting with AJAX?

I'm making a login page in PHP where the user inputs a username. If the username is valid, the user is redirected to another page, where the username they used is printed. If the username is not valid, the page prompts them to enter a valid username and the page reloads.
My problem is in 'POSTing' the valid "username" variable from the login page to the page the user is redirected to.
I know that in my form tags from my login page, I can put:
<form action='pageToPostTo.php' method='POST'>
</form>
However, my problem with this is that, as soon as the user hits submit, this ALWAYS seems to redirect to pageToPostTo.php. As a result, if the username is invalid, I don't know how to avoid this redirection.
Instead, I used jQuery's ".ready" and ".click" to execute javascript code that verifies whether the username is valid when the user clicks "submit." If it's valid, then Ajax's "POST" method is called. If it's not valid, then the login page prompts and reloads.
function isValid(username) {
return true;
}
$(document).ready(function () {
$('input#submit').click(function (event) {
event.preventDefault();
if(isValid(username.value)) {
postUser();
}
else {
alert("Invalid Username");
location.reload();
}
});
});
postUser() is shown below:
function postUser() {
var username = username.value;
$.ajax({
url: 'pageToPostTo.php',
type: 'POST',
data: {getUsername: username}, // username = "danny"
success: function(response) {
alert(response); // Outputs: "Your username is: danny"
window.location.href = 'pageToPostTo.php'; // Outputs: "Your username is: Notice: Undefined index: getUsername..."
}
});
}
"alert(response)" within the "success" function of my Ajax post object properly evaluates $_POST['getUsername']. This shows me that my Ajax post is working perfectly.
THIS IS WHERE MY PROBLEM IS: As soon as I redirect to pageToPostTo.php, $_POST['getUsername'] stops evaluating and instead returns "Notice: Undefined index: getUsername".
Ajax's "post" method seems to work but the redirection is missing what Ajax "posted."
Is there a way to redirect to "pageToPostTo.php" after the Ajax "post" method executes, such that after the redirection, I can retrieve what has been posted by Ajax with $_POST['getUsername']?
If not, why not and what alternatives do I have to get the same functionality?
Previously I was using localStorage.setItem("usernameStorage", username.value) and localStorage.getItem(...) to transfer variables between by php files. Are there any disadvantages to doing it this way?
Snip from my loginPage.php:
<form name="login">
<p>Username: <input type="text" id="username" ></p>
<input type="submit" id="submit">
</form>
pageToPostTo.php:
<?php
$validUser = $_POST['getUsername'];
echo "Your username is: " . $validUser;
?>
P.S. The function to verify whether a username is valid must be in JavaScript.
You just have to start using developed solutions in this case. Like a work around i propose you to use $_SESSION to store your data while you transfer it between the files. In your case: After User login, program validate and if it is success, save it in
$_SESSION['user_id'] = $user_id
after that you make a redirection to your file: pageToPostTo.php: and first of all check if user_id exist in session, if not -> redirect to login page , if exist, assign value to $var and do what you need to do with that.
You have to execute your login php at the same page, and make the redirection ONLY in case if validation was successful. that's is addition to my answer.
You can use form submit instead of button click in jQuery.
Example :
Here is your html form:
<form action='pageToPostTo.php' id="action-form" method='POST'></form>
Modified JQuery Script :
$("#action-form").submit(function(){
if(!isValid(username.value)) {
alert("Invalid Username");
return false;
}
});
In that way, If user name is valid then it will automatically redirect on 'pageToPostTo.php'. There is no need to hit ajax request.

HTML form with PHP - submitting and staying on same page [duplicate]

This question already has answers here:
PHP form - on submit stay on same page
(11 answers)
Closed 5 years ago.
I have a form on a website (www.mywebsite.com). I have a PHP script that sends me an e-mail with information when somebody submits a form on my website. But with action="submitform.php" in the form, it updates the site to the URL www.mywebsite.com/submitform.php. I would like it to stay on the main site (index).
The solution for this: I added header("Location: http://mywebsite.com"); die(); to my PHP code. In this way, users will be redirected to the main site when they have submitted code.
However, this pose a new problem.
Whenever someone submit the form, I would like to display a message such as "Mail has been sent". To make this work, I tried to have a small JavaScript code, basically
document.getElementById("message").innerHTML = "Mail has been sent."
... and <div id="message"></div> to my HTML code. Which works...... However, due to my PHP script redirecting me to my website (with header) when someone is submitting the form, the message will only be displayed for like half a second or something.
Anyone know any workarounds for this? Thanks in advance. I can provide more detail if needed, but my problem should be clear from this. Hope anybody is able to spot my mistake...
I use javascript and ajax for most of my form post. Works wonderful.
Ajax can grab the form information in a form object or pass it as an array. URL is your php proc page, there it will come back with whatever you "print/echo" in a data object that is passed into the success function.
Use this in your HTML,
<input type="button" onclick="submitForm();" value="Submit">
Javascript,
function submitForm(){
//Validate INPUT first. Then grab the form.
form = new FormData($('#frmIdHere')[0]);
$.ajax ({
type: 'POST',
dataType: 'text',
url: url,
data: form,
success:data => {
//Success message here.
//clear form here.
},
error: () => {
// error message here.
}
});
}
php process file use,
$inputFromForm = (isset($_REQUEST["NameOfInputFromForm"])) ? strip_tags($_REQUEST["NameOfInputFromForm"]) : "-";
Without using Ajax (which means you can send the form without refreshing the page), you have two options. Either send the form to a different file, process it, and redirect back - but with a GET parameter to indicate success or failure. Alternatively, just post to the same page (so the handling of the form happens in the same page - I recommend the first alternative).
If you want to use the post-redirect-get pattern, you would use
header("Location: /?status=success");
exit;
when the form was successfully handled in your submitform.php file.
Then you just check what the message in $_GET['status'] was, and display the message accordingly in your index.php file.
if (isset($_GET['status']) && $_GET['status'] == 'success') {
echo "Your message was successfully sent!";
}
This logic can be developed further to have different parameters, to post messages for success and failure, if that's needed for the application.
assumption: you want the user to stay on the page with the form.
in that case you probably don't return false / stop event propagation in your calling code.
let's say, you call your ajax like this:
<form onsubmit="submitform(this);" ...>[form]</form>
onsubmit does the following, it executes anything that is in it's attribute value (submitform(this)) and if it returns some non-false value, it will actually do the action of the form, as if the onsubmit wouldn't have existed. I assume this is exactly what's happening in your case.
To avoid this:
<form onsubmit="submitform(this); return false">[form]</form>
the return false will stop the form from being submitted, after it was already submitted by ajax. this also has the benefit of still working, if the user has javascript disabled.
if my assumption is false however ...
if you want to refresh the page, don't even use ajax and just add a parameter to the url that triggers the message to show. or add the message to the session in php and clear it out of there after displaying.
To doing this, You can use a SESSION var to store message send type (success or failed) and test it everytime on main page, if exist, display message and unset $_SESSION var !
Like this :
MAIN
if(isset($_SESSION['message'])){
if($_SESSION['message'] == 'success'){
echo "Yeah !";
}else{
echo "Problem";
}
unset($_SESSION['message']);
}
MESSAGE
if(mail()){
$_SESSION['message']='success';
}else{
$_SESSION['message']='error';
}
You can set interval and then redirect them to desired page.
<script>
setInterval(function(){ window.location.href="http://mywebsite.com" }, 5000);
</script>

Is it possible to detect a form submission on a page and do my action and then have the form continue as it would normally?

I am building a Landing Page A/B Test plugin for WordPress.
My goal is to set up some rules which when met will record a conversion on the current landing page A/B testing variation.
A couple of ideas I have had so far....
1) JavaScript Event Handlers
With JavaScript, detect the submit event and fire an AJAX post to record my conversion inside a event handler. In the AJAX success callback I will then have it continue on with the post. One method was to set a flag variable to false and then in the AJAX success set it to true. Then it would trigger a submit on the form again but this time the flag var would make it bypass the AJAX conversion save and instead just do the normal form post action.
2) Change FORM Action URL to route POST through local server and then forward to destination
With JavaScript, find all matching Forms in the DOM and replace there post action URL with a new URL which is on my server. THe new URL would make the Form post to my server so that I can detect the post with PHP and record the conversion and then after that I will re-post the original form post data to the original URL.
A Form action URL like this: https://www.remote-server.com
would become
https://www.local-server.com/?record-conversion=yes&id=123&original-url=https://www.remote-server.com
Then in PHP I can get the FOrms original post URL from $_POST['original-url']
To forward the POST to the original URL I have come across 2 PHP functions...
Version 1
Prints the form POST data to the HTML page as hidden Form fields and then using JavaScript it triggers to submit the form right away posting the data to the original URL.
function redirect_post2($url, array $data)
{
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function closethisasap() {
document.forms["redirectpost"].submit();
}
</script>
</head>
<body onload="closethisasap();">
<form name="redirectpost" method="post" action="<?php echo $url; ?>">
<?php
if ( !is_null($data) ) {
foreach ($data as $k => $v) {
echo '<input type="hidden" name="' . $k . '" value="' . $v . '"> ';
}
echo '<input type="hidden" name="test" value="testval"> ';
}
?>
</form>
</body>
</html>
<?php
exit;
}
Version 2
This version uses PHP's stream_context_create(), stream_get_contents(), and fopen() to forward/post the POST data to the original URL.
/**
* Redirect with POST data.
*
* #param string $url URL.
* #param array $post_data POST data. Example: array('foo' => 'var', 'id' => 123)
* #param array $headers Optional. Extra headers to send.
*/
function redirect_post($url, array $data, array $headers = null) {
$params = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data)
)
);
if (!is_null($headers)) {
$params['http']['header'] = '';
foreach ($headers as $k => $v) {
$params['http']['header'] .= "$k: $v\n";
}
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if ($fp) {
echo '<pre>';
echo #stream_get_contents($fp);
echo '</pre>';
die();
} else {
// Error
throw new Exception("Error loading '$url', $php_errormsg");
}
}
Problems/Issues/Concerns
If I use the JavaScript event handlers to detect the form post and record my conversion with. I am not sure what would happen when other event handlers that exist for the same form post/submission exist. I am not sure if it would make mine not run? If mine does run and he others do too. The other handlers might submit the post and then mine could result in the form being submitted more than 1 time!?
If the Form uses AJAX to submit its post. Then my code would be trying to do a page redirect post and break the functionality!
Is my goal even possible?
So this leaves me asking the question. Is it even possibble for me to plugin to a page with existing Forms and be able to record my conversion when the form is submitted and have the Form still perform exactly as it does with out me trying to interfere with it?
To expand on my comment...
If you have no prior knowledge of how the form works, you can get close - and cover the vast majority of cases you'll see in the wild - but there are going to be some scenarios where you will break the form.
Let's say you do all of the following:
Detect target form
Iterate all elements, recording all event handlers
Clear said event handlers (without somehow breaking validation...)
Add your own event handler to the form submit and all buttons (let's hope the form wasn't submitted by typing a specific value or something else weird, and that all buttons actually did submit the form)
Wait for a click
Record the button/event
Do your AJAX call
On success (let's ignore what happens on failure)
Restore all the original events handlers
Attempt to "replay" the event you recorded against the element that your method was invoked from
Cross your fingers
That would cover a lot of cases (certainly all the "normal" html form uses), however, it would break in any of the following scenarios:
Form submission was time-dependent
Buttons on the form did something else entirely (like make an Ajax request to validate a username)
Specifics of the event details are used to process the form somehow (eg where on the button a click occured)
Doesn't handle cases where there's no "click" submission at all (when a specific value is typed into a field, etc...)
Doesn't handle cases where the submission is invoked from outside the form
It would also break any validation events, etc.
You could be less aggressive when stripping events out, but then you're more likely to miss the submission entirely.
A different approach which is marginally better...
If your own methods are robust enough to survive being called multiple times with no side-effects, you might be able to get away with doing the following:
Replace all form onsubmit event handlers with your own wrappers that do something like
function handleSubmit(form) {
// Make your ajax call
$.ajax({
...,
onsuccess: {
form.submit();
}
})
}
That should handle the "stock" case. Then, to handle the case where the original form uses jQuery Ajax, set up a jQuery.ajaxPrefilter() to do something similar (but in this case, instead of submitting a form, you'll invoke the original callback).
Now you're handling stock forms and jQuery AJAX. Of course, if they're using react/angular/a different framework, you'll need to add a handlers for those.
I suppose you could go whole-hog and try to substitute the low-level XMLHttpRequest (and associated equivalents in different browsers) but that's going to be really fragile.
At the end of a day, you'll be signing up for an arms race and I don't think it's one you can ever win.
You need to set up onsubmit attr. at the form.
html
<form onsubmit="Get();" method="post" action="example.php">
<input type="text" name="name" placeholder="name">
<input type="submit" value="Go">
</form>
javascript
var Get = function(){
//action to do
return true
};
100% tested.on chrom dev.
If you want to run the ajax and then if true is answer continue the form then you need to change the javascript to this:
var Get = function(){
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if (xhttp.responseText == "true"){
return true;
}else{
alert("There is some error in verfication.");
return false;
break;
}
}else{
alert("Oops error " + xhttp.State + " happends.");
return false;
break;
}
};
xhttp.open("GET" , x, true);
/* add
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if using post*/
xhttp.send();
};
Instead of x in xhttp.open(); type the file as string.
If caching is not an option then change GET to POST, its slower but secure.
0% tested

Blank Field Tracking

I am trying to track the fields that are left blank on my website form when it is submitted.
The form I am using is used by my sales agents, and since I do not immediately see the submitted info before the sales agent has a chance to modify the submitted information, I am looking to see if they are filling out all of the info on the site instead of adding in more info later in the CRM. This will help me to optimize the form for their use. Currently the form is written using HTML, PHP, jQuery and AJAX.
I have not tried anything yet, as I do not even know where to begin with this. I have not seen it done before.
Let me know if you need to see the markup or if this question needs more clarification. Feel free to point me in the direction of a tutorial if that is easiest.
Thanks for the help!
That is what PHP empty() is for:
if (empty(trim($_POST['some_field']))
{
// Nothing was supplied.
}
So, you could create an array of 'required' fields like this:
$required = array('this', 'that', 'the', 'other');
...and then loop through them:
$errors = false;
foreach ($required as $field)
{
$field_value = isset($_POST[$field]) ? trim($_POST[$field]) : null;
if (empty($field_value))
{
$errors[] = 'The "' . $field . '" field was not submitted.';
}
}
if ($errors)
{
// Do something now that you know there are missing fields.
// Here, we're sending an email...
$subject = 'These fields were not filled out';
$body = 'The following errors occurred: ' . implode(', ', $errors);
mail('email#example.com', $subject, $body);
}
I think that you want to know the way how to check and validate the form information before submit. And as you said that you use jQuery, so I advise that there are 2 solutions to solve the problem at least.
1, write the validate script by yourself.
you can use the following script to check the form data before submit.
jQuery(form).submit(function(){
// Here you can validate your form data
// and if the data are incorrect,
// you can return false, and the form submission will be cancelled
});
2, use the jQuery Validation plugin.
The plugin can be got from http://jqueryvalidation.org/, and you can import it with the following script.
<script type="text/script" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>
And then, you only need to add some special attribute in your form.
For example, if you add "required" of your input field, which means the field must be filled with the characters.
<form>
<input type="text" name="username" required />
</form>
And then, write the following script to notify the plugin to validate the form before submission.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("form").validate();
});
</script>
You can check in both PHP or JS. If you want to do this server side so you can save this information simply check the POST results of the form.
if (trim($_POST['myField'])=="") {
//not filled out. if you have default values, check for it in the if above too.
mail('your#email.com', 'Subject', 'Your body.');
}

Javascript return issue

This problem has just become apparent in some historical code and seems to be an issue relating to IE8 + and FF4 +
I have a js file that validates a contact form, one particular section calls a function to open a new window with some info for the user. At this point the script seems to ignore my valid = false variable (which is flagged to stop form submission)
function showFormat() {
var myWindow;
myWindow = window.open("http://url/page.html","Postcode_Information","location=1,status=1,scrollbars=1,width=640,height=400");
myWindow.moveTo(50,50);
}
Above code is causing the issue. i've tried adding valid=false; return valid; to the end of the function but it is apparently being ignored. Adding this to the begining of the function means that the validity is correct and the form doesnt submit but obviously my new window doesnt open.
EDIT TO EXPLAIN IN MORE DETAIL
My js file has a series of validation functions (checking username, address, email address validity etc). A variable is initialised called valid which will always be true unless any user input does not validate, in which case valid = false.
If valid = false then an if statement is run which checks against a number of variables in order to determine which area of the validation has caused the problem and will flag up an appropriate prompt. Most of these are done via a message box (I inherited this code and am merely trying to get it working) but one prompt opens up a new window. If any of these prompts are called at all then the form should not be submitted.
The problem I am having is that when this new window opens (and this is the only prompt causing this issue) the form will still submit.
See code below for an example of when these prompts are called:
if (!valid) {
if (emailNoAddress == true) {
alert('You have requested to receive more information by email from other company(ies) but have not provided email address details – Please correct this below');
highlightEmail();
}
else {
if (contactDetails == false) {
alert('Please provide your email address details. We will not send you future correspondence and offers by email if you prefer us not to.');
highlightAddress();
highlightEmail();
}
else {
if (postcodeGiven == false) {
if (dataform.pcode.value == "") {
alert('Please enter a valid postcode');
}
else {
showFormat();
}
}
else {
if (questionsAnswered == false || countryGiven == false) {
alert('Please choose an answer from the options provided');
}
else {
//alert(checkstr);
alert('Could you please complete the questions missing details');
}
}
}
}
}
So you see, my function can only be called when !valid in which case the form should not submit but as soon as I execute the new window function showformat() it allows the form to be submitted.
EDIT - UPDATE
I've managed to narrow the problem down slightly in that after the new window opens, no more script is executed (i've tried adding a few alert messages to check the value of valid but they are not shown - I've also tried adding a breakpoint while debugging with Firebug but this is not hit) and the form submits regardless...
EDIT - UPDATE
Beacuse this was a time-critical issue, for the moment I have just put all the text from the pop-up window into an alert and call that instead of the function. When I have any more time to spend investigatin I will update.
Are you having the onsubmit event defined on the form tag? If so then add the keyword return in the onsubmit event like shown below
onsubmit = "return some_function" and in the function called u have to specify return false. Then u will be getting wat u want.
Hope this helps you.
Here is the SImple example which works as u need. Try this and correct ur code accordingly
<html>
<head>
<script type="text/javascript">
function validate()
{
if(document.forms[0].stext.value!="")
{
return showformat();
}
else
return false;
}
function showformat()
{
window.open("new.html","");
return false;
}
</script>
</head>
<body >
<form name="sample" action="onsel.html" method="post" onsubmit="return validate()">
<input type="text" name="stext" id="stext" value="" />
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Hope this helps you

Categories

Resources