So I've set everything up so my contact form submits and I get an email in my inbox. They problem is that every time I refresh the page, or come back to the page, I get ANOTHER copy of the same email in my inbox.
How do I ensure that I'll only get the email once, and also that a user won't accidentally keep sending me messages after they've written and successfully sent the one they want.
I'd also love to know how to make sure the success message isn't just showing ALL the time.
If it's helpful, here are my PHP and jQuery codes:
PHP: https://www.tehplayground.com/Z7mCYfoSz09WEEVj
jQuery: https://www.tehplayground.com/cN9U4HpE0J5czkyS
Thanks for the help!
You can redirect the user to another page, and it will "reset" the form requests:
header("Location: index.php");
document.onload = function () {document.getElementById("form").reset();}
$("#refresh").click(function(){
$("#myModal").find('input:text, input:password, select, textarea').val('') ;
$("#myModal").find('input:radio, input:checkbox').prop('checked', false);
$("#weak").html('') ;
$("#moderate").html('') ;
$("#strong").html('') ;
$("#show_error").html('') ;
$("#show_success").html('') ;
$("#new_password").attr("disabled", "disabled") ;
$("#confirm_password").attr("disabled", "disabled") ;
$("#reset_pass").attr("disabled", "disabled") ;
});
Use the above and it will reset a form .
this is a common problem if you are submitting forms using post. if a user accidentally refreshes a page after submission. it can cause duplicate form submission. read more more about post redirect get pattern here for clarity on what am talking about.so in a nutshell the basic procedure to do here is to redirect the page after submission either to a different page or the same page. like so
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$error .= "<p>• Don't forget to write your name!</p>";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$error .= "<p>• An email address is required. </p>";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["message"])) {
$error .= "<p>• Don't forget to write your message!</p>";
} else {
$message = test_input($_POST["message"]);
}
if ($_POST["email"] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
$error .= "<p>• Please input a valid email! </p>";
}
header('Location: index.php');// redirect so that the pages is recieved through get method
exit()
//note that if you are redirecting to the same page you wont be able to use variable, you can instead use session knowing that the page refreshess
}
?>
I think the best way to handle this issue is to create a unique identifier for each submission.
foreach($_POST as $data){
$s = md5($s . $data);
}
Now $s holds a value of 32 chars in length that is pretty much unique to any input.
You have multiple options:
You can insert this value into a table (2 columns) where 1 is this value and the other the date of insert and delete the record after 1 day.
Use sessions and just append this id to the array (and reset it from time to time)
Any other method of storage, just keep in mind that storing it on the client is not the best way to do it.
This pretty much eliminates double submissions. However this is more or less an example code to give you a general idea. Perhaps not all fields should be used, and maybe you want to add a date() to it as well.
All depends on your needs.
You can use other techniques to do the same thing, this however is something that should be handled by the server and not the client. So using Javascript is an escape goat, just not a permanent solution.
Thanks all. Got it sorted!
I ended up splitting up the PHP into a “process.php” and “form.php”, which has helped with stopping duplicates, and then used an AJAX to effectky refresh and rest the form without refreshing the whole page.
Everything works wonderfully now - although hard to say whether its as secure as it can be!
The best way is to use JQuery to submit the form and email and reset it without refreshing the page . Don't use "form" tag , instead use "div" tag with the same class , otherwise the page will get refreshed and the click event will be called .
Related
I am a PHP newb so please bear with me for this rather simplistic question.
I have a PHP form setup like so >>
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$comments = $_POST['comments'];
if($comments)
$error = "There was an error, please give us a call at ### ###-####.";
else{
if($name=="Name" || $email=="Email" || $message=="Message"){
$error = "All fields are required, please fill them out and try again.";
}else
$header = "From: $name <$email>";
$message = "Name: $name\n\nEmail: $email\n\nMessage: $message";
if(mail("email#domain.com", 'Form Submission', $message, $header))
$success = "Thanks for sending us your message, we'll get back to you shortly.";
else
$error = "There was an error, please give us a call at ### ###-####.";
}
if($error)
echo '<div class="msg error">'.$error.'</div>';
elseif($success)
echo '<div class="msg success">'.$success.'</div>';
}
?>
The basic idea is that the form has descriptive text pre-filled in each field but when you click on them they are cleared via Javascript. I want to prevent people from pressing send on the form without filling it out, hence the "if($name=="Name" || $email=="Email" || $message=="Message"){" bit. However while that message is working the form is still submitting. Why is this. Also please note that the "comments" field is in fact a honeypot. Thanks!
Because php is server-side. You need to look into javascript validation for what you want. To validate with php you HAVE to submit the form.
One tutorial but I recommend Jquery validation
"I want to prevent people from pressing send on the form without filling it out, hence the "if($name=="Name" || $email=="Email" || $message=="Message"){"
All you need to do is disable the submit button client side until the proper validation is met, then also validate server side. As #Iznogood said, that's why your gettin your error
Like lznogood said, PHP validates the form on the server, so you need to send the information to the server before PHP can process it.
If you want the form to be checked on the user side before sending it to the server you should use JavaScript to do that (jQuery is a great tool to use), and after checking it on the user side you can decide whether to send the form to the server or not.
Though this isn't an answer to your question, you might be interest in the new html5 feature placeholder. Read about it here. You can check to see which browsers it works in here (stupid internet explorer!). 5 years ago, I would put those "hints" as the value, which was a pain to validate. placeholder makes it sooooooo much easier. Your tag would look like:
<input type="text" name="email" placeholder="Enter Your Email Here" value="">
Note that value is empty. You can omit the value attribute, I left it in to show it's not needed here.
As far as an answer to your original question, everybody else is correct, javascript is the way to go.
I'm working on a coming soon page. On the page I ask users to signup using their email through a form which then emails their emails to me. I'm not sure how to make sure that the data they are putting in the form are emails (to prevent spam). Any help?
Thanks.
Use jquery validate really easy to use http://docs.jquery.com/Plugins/Validation
Client side js is not enough, you should also validate with PHP's filter_var:
<?php
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$from=$_POST['email'];
}else{
$error['email_to']='Email Invalid!';
}
?>
You shouldn't rely on client-side verification to keep spam and other unwanted registrations out. Although you could use jQuery validate to make the site more UI-friendly for the visitors, providing them with a neat message that the email address entered is not valid, and that they should review that field.
But a spam-bot will not care about that validation from jQuery, it will only post the fields given. That's why you need to validate the data on server-side.
There are several ways to validate email addresses with regex, but not all of them is reliable. Check out http://www.linuxjournal.com/article/9585 This article explains alot of this.
user following code as primary step to validate the email input
if(document.getElementById('Email').value=="")
{
document.getElementById('Email_Msg').innerHTML="Please Enter EmailId";
document.getElementById('Email').focus()
return false;
}
else
{
if(document.getElementById('Email').value.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-Z0-9]{2,4}$/))
{
document.getElementById('Email_Msg').innerHTML="";
}
else
{
document.getElementById('Email_Msg').innerHTML="Enter Valid Email-Id";
return false;
document.getElementById('Email').value="";
}
}
If you want to prevent spam, making sure the email field is filled in with an email field is not enough alone. Consider using a captcha like ReCaptcha
just have a single line validation for your email.
the code may be written like below.
<?php
if(empty($_POST['email']))
{
$error[]="Enter Email ID";
}
else
{
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$error[]= "Not A Valid Email ID.";
}
}
//pass these errors to display ana error message to user.
foreach($error as $i)
{
$message = $i."<br />";
}
?>
use this code some where in your web page.
<?php
echo $message;
?>
Additionaly Use mail function and mysql database (or other if you are using) to send a mail to verify their email id. you can prevent unwanted users from registering. and also use captcha to prevent flooding to your database.
I think this helps. if any doubts reply here.
Create your own captcha using php gd2 library. It's easy and efficient.
I'm developing a form validation class in PHP. When form validation fails, I can easily redirect again to the form's html page but without error information. I would like to redirect to the form's page with the specific errors about which fields failed and why.
How should I do this? Should I send information back via GET or POST? and in which format? Would really to see some code to see how people tackled this problem.
Thanks!
You could use the header() function. So just check the fields that are posted:
if(!$form->valid()){
$msg = "Form is not valid";
} else {
//Don't know if you want this
$msg = "Form is valid";
}
header("Location: [page where you came from]?msg=" . urlencode($msg));
Then in the page where you're redirecting to use
if(isset($_GET['msg]))
echo urldecode($_GET['msg']);
to echo the message. If you are using other get variables in the location of the header function, of course, use &msg=" . urlencode($msg). (You may also want to return the values that the user submitted, so the user doesn't have to fill out the entire form again if he makes 1 mistake.
I agree with user187291's suggestion of using $_SESSION because:
It doesn't hijack the URI like using $_GET (you would never want a static link to a status message). Users could press "back" to the page with your form and still see a status message because the URI says so.
Print and unset it in the same run, you won't be able to use it more than once (which is what you want?!)
If you're going with AJAX, $_GET is more widely used for retreiving values, which you are doing from the validation controller.
there are number of approaches
pass errors in GET when redirecting back like you said
use sessions to store error info, on the form page check Session for errors
do not redirect after failure, just output form again along with error messages
ajax submits
which one to use depends on the application. For most apps sessions method is most appropriate.
Something like this:
// Pseudo Code
function isValid($parm) {
$return = false;
if(preg_match(/^[a-zA-Z]+$/, $parm) {
$return = true;
}
return $return;
}
$firstname = $_GET["fname"];
$lastname = $_GET["lname"];
$validFirstName = isValid($firstname);
$validLastName = isValid($lastname);
if($validFirstName == true && $validLastName == true) {
echo "It's all good";
// Do what you need to like, Submit
} else {
echo "Please retry";
// Display error message
}
I use a class to interface with $_POST, similar to the following:
// create the object
$post = new PostData();
// register your requirements... write whatever methods you need
// for each call,read $_POST, check criteria, and mark the field
// as good or bad...
$post->required ('LastName');
$post->required ('FirstName');
$post->numeric ('Age');
$post->optional ('MiddleInitial');
$post->regExp ('/\d{3}/','AreaCode');
$post->email ('Email');
// check the status
if (!$post->isValid ())
{
$_SESSION['FailedPostData'] = $post;
header ('Location: page.php');
}
// normal form processing
Then, on page.php, you can see if FailedPostData is in the session, read it to find the info entered last time, as well as which fields that failed. I use a template engine with macros that let me easily re-populate the form inputs and mark the failures. Otherwise you might end up with lots of code for a simple form...
You'll also need a mechanism to be sure that stale FailedPostData doesn't hang around in the session and confuse things.
I am doing it this way. Beginner in php so not sure if this is the best way to do:
HTML Form Page:
<form id="abc" method="post" action="validate.php">
PHP Page
..validation conditions..call a function if things do not match
function display_error($error) {
echo "<html><body><link href='style.css' rel='stylesheet' type='text/css'><br><center><h2>";
echo "$error";
echo "</h2></center><br><br>";
echo "<center><input type='button' value='Go Back' onClick='history.go(-1)' style='width:100px; height:28px; font-size:16px'></center>";
echo "</body></html>";
}
Clicking on the back button takes you back to the html page with the data intact.
In Yahoo or Google and in many websites when you fill up a form and if your form has any errors it gets redirected to the same page.
Note that the data in the form remains as it is. I mean the data in the text fields remains the same.
I tried ‹form action="(same page here)" method="post or get"›. It gets redirected to the page, but the contents of the form gets cleared.
I want the data to be displayed.
You know how tiresome it will be for the user if he has to fill up the entire form once again if he just forgets to check the accept terms and conditions checkbox.
Need help!
You need to do this yourself. When the page gets posted you'll have access to all the form values the user entered via $POST['...']. You can then re-populate the form fields with this data.
Here is a modified version of what I use for very simple websites where I don't want/need an entire framework to get the job done.
function input($name, $options = array()) {
if(!isset($options['type'])) $options['type'] = 'text';
$options['name'] = $name;
if(isset($_POST[$name]) && $options['type'] != 'password') {
$options['value'] = htmlspecialchars($_POST[$name]);
}
$opts = array();
foreach($options as $key => $value) {
$opts[] = $key . '="' . $value . '"';
}
return '<input ' . implode(' ', $opts) . '/>';
}
(I have a few similar functions for <select> and <textarea> and so on)
When you're building fields you can do something like:
First Name: <?=input('first_name')?>
Last Name: <?=input('last_name')?>
Password: <?=input('password', array('type' => 'password'))?>
If you process your forms in the same page as the form itself, they will get auto filled if there are any errors. Most frameworks, though, do all of this for you (and in a much better way than the code above), I personally suggest CakePHP or CodeIgniter.
This is not done automatically. They get values from post / get and then assign the values the user typed to the template. What you see is html that was generated from the script that handled user values.
If you put your form and the form data processing in the same script, you can easily print out the data that has already been entered in the form, e.g.:
$valid = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['name']) && $_POST['name'] == 'Hugo') {
$valid = true;
} else {
echo '<p>Seriously, you have to enter "Hugo"!</p>';
}
// more data processing
if ($valid) {
echo '<p>Everything’s fine!</p>';
}
}
if (!$valid) {
echo '<form action="" method="post">';
echo '<p>Please enter "Hugo": <input type="text" name="name" value="', (isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''), '"></p>';
echo '<p><input type="submit"></p>';
echo '</form>';
}
Well this is not nice example but that’s how it works.
a lot of frameworks do this job for you, so dont waste your time doing this manually
You'll have to check the data within the same file, and if it is correct, then you redirect to the correct location. Then you can use the $_POST or $_GET information the user posted and he can fix the error(s).
You can use two approachs (they're not mutually exclusive):
Use JavaScript to help the user before he submits the form. That way, you save a roundtrip to the server.
What you asked for:
In the form, fill the value attributes of the fields with the data sent back from the server. For example: you send a field name, which you get as $_POST['name'] in PHP (assuming you used method='post'. If you send back the data and modify that field adding value='<?php $_POST['name']; ?> you should get your data back.
If you're using a template or framework system (I've incorporated the Smarty engine into several projects of mine), you can usually tweak the templates so they automatically fill fields with values if they detect that the $_POST[$variable] value corresponding to their field is set.
As for the passwords, as far as I understand it (I could be wrong): it's a convention that minimizes the amount of time that password is being sent over the wire, hence shrinking the window for anyone who may be sniffing to pick up on the text. It's just good practice to leave password fields blank, is all.
I've got a submission page in php with an html form that points back to the same page. I'd like to be able to check if the required fields in the form aren't filled so I can inform the user. I'd like to know how to do that with php and javascript each. However, I imagine this is a common issue so any other answers are welcome.
Do the check in posting part of your php
if(isset($_POST['save']))
{
$fields=array();
$fields['Nimi'] = $_POST['name'];
$fields['Kool'] = $_POST['school'];
$fields['Aadress'] = $_POST['address'];
$fields['Telefon'] = $_POST['phone'];
$fields['Email'] = $_POST['email'];
foreach ($fields as $key => $val)
{ if(trim($val)=='')
{ $errmsg=$key." is not filled!";
break;
}
}
}
if($errmsg == '')
{ //do your saving here
exit();
}
if(!isset($_POST['save']) || $errmsg != '')
{ //show your form here
// and make it to return to the same page on submit
//<input name="save" type="submit" value="Save" onclick="return true;">
}
For extra credit, once you know how to do it in PHP and JavaScript from Riho and annakata's answers, then build a way of defining a field constraint in a single form that can both be rendered as JavaScript for client-side validation and run on the server.
Since you need both (client-side for user convenience, server-side because we're really very much past trusting the client at this point), it seems like quite a decent idea to support both from a single infrastructure.
As far as JS goes you have to check before you submit. Generally this involves binding some validation function to the onsubmit event trigger of the form, and that validation function will consist of some tests for each field you're interested.
Most JS libraries have validation implementations that will do most of the work for you, which sounds like it might be a good idea for you. Googling "client side validation" will yield infinite results, but this (I'm library agnostic, read and choose for yourself) should get you started*:
http://blog.jquery.com/2007/07/04/about-client-side-form-validation-and-frameworks/
http://tetlaw.id.au/view/blog/really-easy-field-validation-with-prototype/
http://dojotoolkit.org/book/dojo-book-0-4/part-4-more-widgets/forms/validation
*this is on the teaching you to fish plan
The LiveValidation library would help you out a lot:
http://www.livevalidation.com/