Simple Honeypot Form Check with PHP and AJAX - php

I've been trawling through all the suggested posts for this topic but can't seem to find a solution that either works for me or I quite understand.
I am just trying to do a simple honeypot which checks if a hidden field is filled in by bots and breaks the form if so. My problem seems to be when it comes to using AJAX to see if the PHP value cleared. Hope that makes sense as I'm not well versed in coding languages.
My original idea was to disable the submit button for any bots that fill out the field. However seeing as the field is blank straight out the form loads the submit button and the point is lost.
This is the part of the form checking for the bots:
<!-- THE HONEYPOT -->
<li id="artificial-detect">
<label for="artificials">If you see this, leave this form
field blank and invest in CSS support.</label>
<input name="artificials" type="text" value="">
</li>
<!-- /HONEYPOT -->
<?php
$spam = $_POST['artificials']; // This is our Honeypot field
if($spam) { // If the Honeypot field has been filled in
die("No spamming allowed bitch!");
} else { ?>
<li class="last">
<input class="submit" type="submit" name="submit">
</li>
<?php } ?>
I don't understand what to do now:
jQuery.('#salesforce-crm-form .submit').click(function(){
jQuery.ajax({
// Get PHP function that determines whether the honeypot has been snatched.
});
});
I am using an external URL for the action="" so I thought maybe that could only be inserted if the PHP returns clean of bots.

You cannot do the things in the order you think.
First PHP runs to deliver your form.
Then the browser acts, displays the form to the user. He might enter data and send it back.
Then PHP is on again, checking the form values.
You pretty much have the code you want to check if the honeypot field is filled. You should not try to use AJAX, because this PHP check can only be taking place after sending the form. Simply don't do what the form is intended to do if you detect spam.
BTW, Bots dont press submit buttons. Bots send Request based on parsing forms, disabling all Javascript.
[EDIT]
If your form goes to an external URL, then you cannot control any spam detection. Because bots do not use Javascript, anything on this level will not work, either, but thats what you are trying to do.
Only thing that will work is to NOT send the form to the external URL directly, but to a PHP script on your server that will check for spam an then send it to the original destination. Don't know if this will mess up anything else because now it is not the users browser sending the form, but your server. If there is any detection and/or usage of request metadata on that side, you are interfering with this.

Put default value in honey pot input and ask user to delete it before post. Also there is no use for disabling submit button:) Bots do not work this way, they will simply submit form without clicking anything.

If you change the type of the input box to hidden, and give it an ID, like so
<input name="artificials" type="hidden" id="honeypot" value="">
then users will not be able to see the input but bots will fill it in.
Then in your javascript, using jquery you can check for a value like so
var honeypot = $('#honeypot').val();
if(honeypot == '' || honeypot == null) {
// Call ajax function
}
Note, that has not been tested and is only an example.

Related

Onblur or onchange check, using a php function in a registration form

I would like to be able to check the text in a text-box after it has changed, and report what is wrong.
It is for a registration form.
This is a part of register.php where
<form action"" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p><input name="username-field" type="text" onblur="someFunction()" /><span id="UsernamehelpText"> </span>
</li>
</ul>
</form>
Then I would have a registerfunctions.php where i would store all the functions for checking lenght,char,maybe regex etc.. Its not really that important what functions i call. I just don't know how to call them.
Form what i have seen the span is where u post the errors, but if there is any other option im open for it, all i want is to be able to post the erorr text in the same line as the text-box
I have checked JavaScript and AJAX, but I am pretty new in this and don't really understand how it works.
After discussion in comments I understand what you want.
First, an explanation. There are two places where validation occurs: In your frontend (your web page) and in your backend (in the PHP script that saves the posted values). Anything that you really don't want to save - for example unescaped SQL strings, too-long fields, and so on - has to be validated in PHP, because it is trivial to get around Javascript validation. For example, nothing is stopping someone from sending a POST to your server containing illegal values without even bothering to visit your webpage.
Even though you need to perform validation in the back-end, it's still user friendly to do the same validation in the front end, so the user doesn't have to wait as long to see an error. This also reduces traffic to your server. Something you probably want to do in a big project is to have some kind of system for writing validation rules centrally, and then using those rules to dynamically generate both PHP and Javascript validation. The advantage of doing that is that you don't duplicate your business rules in two places, but in a smaller project it's probably not worth the hassle.
Validation in the frontend looks about like this: You bind an event handler to an appropriate event or events (you can add onkeydown="validateUserName()" for example, so that the validation reacts a bit quicker), and update your warning text appropriately.
<form action="" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p>
<input id="username" name="username-field" type="text" onblur="validateUserName()" />
<span id="UsernamehelpText"></span>
</li>
</ul>
</form>
<script type="text/javascript">
function validateUserName() {
var userNameElement = document.getElementById('username');
//Do your work: Get the value of the user name field, check
// the values against your validation rules...
var helpText = document.getElementById('UsernamehelpText');
if(isValid)
helpText.innerHTML = "";
else
helpText.innerHTML = "Invalid!";
}
</script>
In the backend, when you process the form, you then have to check the same rules in PHP to prevent illegal values from being posted either maliciously or due to an error in your Javascript. If an error is found, you don't save, instead you can just re-render the form with the submitted values in the input fields and a message indicating what was invalid - this allows the user to change their inputs without losing the values they submitted.
With jQuery it would look something like this:
function someFunction() {
$.ajax({
url: "checkStuff.php",
data: $("input[name='username-field']").serialize,
success: function(data) {
if (data == "correct") {
$("#UsernamehelpText").html("Valid");
} else {
$("#UsernamehelpText").html("Invalid");
}
}
});
}
Your PHP could be something very simple that just checks the validity of the input and then echos "correct" if it is.

How to cause a form field to be required

Is there a way to make a field required for form submission?
I can use HTML, Javascript or PHP to do this - whichever works.
I want to ensure that a form is not submitted with a blank value. Also it would be nice if I could make it so that users HAD to input values into certain fields.
EDIT: I don't really want to use jQuery at the moment as I'm not sure that my boss wants me to use jQuery.
Tried to do this:
<script type="text/javascript">
$('addorg').submit(function(){
if($('orgname').val()==""){
alert("Organization Name must be Filled");
return false;
}
})
</script>
And here's the HTML it is working on:
<form name="addorg" action="addorg.php" enctype="multipart/form-data" method="POST">
<div id="orgdiv"> <fieldset><label for="orgname">Organization Name</label>
<input type="text" name="orgname" id="orgname"/>
</fieldset>
</div>
This is for client-side validation. I can handle server-side validation, my PHP is far better than my Javascript or jQuery.
The client-side validation did not seem to work.
Nothing will ever prevent a form from being submitted to your web server. You can submit anything you like using tools like Curl. Therefore, you must always validate on the server. For normal users, you can put JavaScript in your page that blocks submitting invalid forms.
Therefore:
Is there a way to make a field required for form submission?
No.
I want to ensure that a form is not submitted with a blank value. Also it would be nice if I could make it so that users HAD to input values into certain fields.
You cannot. However, #Nicolas's answer shows how you can add client-side validation to block typical users from submitting the form and server-side validation to block everything else. His approach is correct.
You can do this in either JavaScript or PHP. JS is more user friendly and easier to code, but can be bypassed by determined users. It also may not function on some browsers or with some settings allowing users to continue as if there were no validation, but those cases are usually rare. I would recommend a JS solution unless this is a corporate website or has no room for error.
You can do this by modifying your form tag with an onSubmit function:
<form action="whatever" method="post" onSubmit="checkStuff();">
<input id="field_1" name="field_1"...>
You then need to create that function and place it in the head of your page. It should read something like:
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if (document.getElementById('field_1').value == '') formOkay = 0;
...
// Let the user know something is wrong somehow. An alert is easiest.
alert('fill out everything, ya goof!');
// If you return true the form will submit. If you return false it will not.
if (formOkay == 1) {
return true;
} else {
return false;
}
}
Note that your inputs must have an id attribute for this approach to work (though it's possible to modify my code to work with names too). I would make the id the same value as the field name. You can add additional checks for more fields where I placed the ellipsis. This code could be written more efficiently and cleanly, but I thought this approach would be easiest to understand and modify.
This is off the top of my head and hasn't been tested, but should get you working down the right track. If you have additional questions, please let me know.
EDIT:
I just wanted to follow up to agree with others that if you have the time and inclination, or this is a work related issue, you should validate both ways. JS provides a better, more user friendly method, while PHP insures nobody can just circumvent the JS to break your rules.
I don't know PHP, but your pseudo code would be something like this:
if field_1 = "" then
// Option 1
Print("Please press back and fill out field 1!")
AbortPage()
// Option 2
Redirect("form.php?error=Please fill out field 1&[other form values]")
end if
In the case of option 2 you would modify the form page to detect url variables and place them into the inputs. You would also modify it to look for a url variable called 'error' and display the contents if found.
Javascript should do it easily. Here's an example in jquery.
<input id="required" type="text />
Then, in your javascript library, you have something like:
if($("#required").val().length!=0)
{
formsubmit();
}
else
{
alert("You left the required field blank");
}
$('form').submit(function(){
if($('thisemptyfield').val()==""){
//do stuff
return false; //will cancel form submission
}
})
Makes that if thisemptyfield is empty, the submission of the form is cancelled. I encourage putting up a flag telling your user to fill in the field before submitting. Because with that code only, nothing will happen on the page. It just wont submit until the form is submitted with a value in the field.
Edit: This is using jQuery.

Showing an alert() dialog box if a form does not have valid values

I have a simple form which accepts a Title and a Contents variable from a textbox and a textarea. The form will send its data to a file called add-post.php. However, I am looking for a way to alert the user that either the textbox or the textarea has invalid data (is empty) in case they click the submission button.
I was thinking that an alert() popup box would be the best idea because it doesn't redirect to any other page and the user never loses their data (imagine they entered a whole lot of text but forgot a title. Sending the data to add-post.php and performing the check there will result in loss of data for the user).
However, I'm not sure how to actually implement the alert() popup. How would I make it so that the check is done AFTER they have clicked the submit button but BEFORE the data is sent off to the next file. Any advice is appreciated.
On your form add something like this
<form name="frm1" onsubmit="InputChecker()">
Then in javascript
<script type="text/javascript">
function InputChecker()
{
if(document.getElementById({formElement}) != '') { // not empty
alert("This element needs data"); // Pop an alert
return false; // Prevent form from submitting
}
}
</script>
Also as others have said jQuery makes this a little bit easier. I highly recommend the jQuery Validate Plugin
Some people do find the alert box "annoying", so it may be better to append a message into the DOM to let the user know what needs to be fixed. This is useful if there are numerous errors as the errors will be more persistent allowing the user to see all the things they need to be fixed. Again, the jQuery Validate plugin has this functionality built in.
Attach an onsubmit event to the form, and return false; to stop the submission if checks fail.
Form validation with Javascript. Or easier with jQuery.
Basically, validate the form when the submit button is clicked (with an onsubmit handler), and then use an alert() box if needed. By the way, people usually hate alert boxes.
You have a number of options when it comes to client side validation. This is just one.
<form id="tehForm" method="post">
<input type="text" id="data2check" >
<input type="button" id="btnSubmit" />
</form>
<script type="text/javascript">
function submit_form(){
if(document.getElementById("data2check").value!="correct value"){
alert("this is wrong");
}else{
document.getElementById("tehForm").submit();
}
}
</script>
For a more indepth example check out this link

Checkbox that submits form on click

I'm using Codeigniter and wants to know how I can make a checkbox that submits the form on click?
Secondly, this checkbox will be one of several checkboxes that will act as a filter like products > $20, products < $30, how do i pass it in the url? I'm thinking /1+2+3
Haven't worked with Codeigniter much, but I can answer how to make the form submit on checking the checkbox with JS:
<form id="something">
<input type="checkbox" name="foo" id="foo" value="yes" />
</form>
<script type="text/javascript">
$("#foo").click(function() {
if ($(this).is(":checked"))
$("#something").submit();
});
</script>
The javascript questions seem to have been solved already; let's step to the codeigniter ones.
You can pass the url in one of those two ways.
Idiomatic but limited: as /1/2/3/4/etc. The controller function handling that url could both use func_get_args to read them or, if you already know how many parameters will be passed at the most, give a default value of null to all non-necessary paramenters;
Not Codeigniterish but seriously better for search parameters: enable the query strings on your config file, pass arguments as you would normally with GET (min=2&max=3 and so on) and get their value with CI's input class ($min = $this->input->get('min')).
This has nothing to do with PHP, nor CodeIgniter. The solution is to submit the form in the onclick event of the element.
<input type="checkbox" name="filterx" onclick="document.forms[0].submit()" />
You can use the OnSubmit event of the form to nicely format the url, if you like.
To do this, you can
get the values of all desired elements,
build a nice url from it,
set the url using location.href = yourniceurl,
cancel the regular submit by returning false.
Note that both solutions require javascript to be enabled. So it is a good thing to have other means of submitting the form (submit button). Don't rely on submitting by pressing Enter. Opera will use the Enter key for toggling the checkbox instead of submitting the form.
If you like, you can hide the submit button using Javascript, that way, users having Javascript will have their form auto-submitted, while users without can use the button.
You will need to make sure that your server side form validator not only accepts the nice url, but the ugly url (which posts values like ?filterx=on) too.

Secure solution to hidden forms

I have this code:
<? if ($cur_post['poster_id'] == $forum_user['id']) { ?>
<div class="txt-box textarea required">
<label for="fld<?php echo ++ $forum_page['fld_count'] ?>"><span><?php echo $lang_post['Write message'] ?> <em><?php echo $lang_common['Required'] ?></em></span></label>
<div class="txt-input"><span class="fld-input"><textarea id="fld<?php echo $forum_page['fld_count'] ?>" name="req_message" rows="14" cols="95"><?php echo forum_htmlencode(isset($_POST['req_message']) ? $message : $cur_post['message']) ?></textarea></span></div>
</div>
</div>
<? }
else { ?>
<? } ?>
I need a more secure solution to hidden forms, because currently with this code when I press submit (as an admin) it says I must enter a value for the written message.
I can bypass this using hidden forms under the ELSE bit - but people with any knowledge can just bypass this using Inspect Element or Firebug and then post that value.
I need a more secure solution to this, so that people cannot edit Hidden forms. Do I post the old variable somehow to the form?
It's for a PunBB page (edit.php): http://punbb.informer.com/svn/punbb/tags/punbb-1.3.3/edit.php (original).
Thanks
This is always an interesting problem.
I suggest storing private data in the users $_SESSION with an index unique to the form + page call. I just came into a similar problem at work where I was starting to pass way too much private data through hidden form fields. Now I simply pass a unique id which I use to index the specific private form data in the session.
It's not a 100% solution. Storing the data in the session rather than in the form means a stale form can timeout (ie if the session is killed/timed out), but it's a worth while trade off I think.
I'm not entirely sure I understand the question. Are you trying to control how the form renders, or trying to figure out how to add 'sensitive' data the a form?
First, if you're worried about what parts of the form are being rendered on the page, anything in the else clause would only render if the conditions in the if clause were not true. The else is not 'hiding' part of the form.
Second, there is no such thing as a 'secure' client-side form. Generally speaking, you cannot control what data is submitted to your application, and anyone can submit any POST or GET data they want. Instead you have to handle it on the server-side by properly filtering to ensure that a user has the proper authorization to do what they're trying to do. It sounds like you need to require the user to identify as an admin when the form is processed (most likely through session data).

Categories