How can I validate my form without using JavaScript? I have used the required HTML 5 attribute but as IE doesn't support IE (ANNOYING) is there a way around this with using PHP which will take time.
Thanks
You should always validate on the server side (e.g., with PHP). There are probably a lot of libraries that will make this easier and save you some time, but the principle's pretty simple:
if (isset($_POST['submit'])) {
$name = isset($_POST['name']) ? $_POST['name'] : null;
}
$errors = '';
if (!$name or strlen($name) < 5) {
$errors .= 'Name must not be empty and at least five characters';
}
if ($errors) {
echo $errors;
}
else {
//Store data from the form or whatever you want to do.
}
I would also recommend using Post/Redirect/Get
You can use PHP to validate using the server:
http://thinkvitamin.com/code/php-form-validation/
Only server side validation (ie in PHP) or using javascript. Although, I'd go for the server side part - it is the safest, since a bad user could forge bad data from the client side
Related
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 .
I'm trying to get two forms into a single script.
The script would allow you to click on a login button and have a form populate, fill out the form and then create cookies. The 2 forms work really well separately but I'm having issues combining them.
The script is about 180 lines so I'm not going to include all of it.
I'll include the main lines though:
<?php
if (!isset($_COOKIE['email']) || !isset($_COOKIE['password'])) {
if (!isset($_POST["login"])) {
// create form buttons here
} elseif (isset($_POST["login"])) {
if (isset($_POST["submit"])) {
// create form
// php code and create cookies if correct
} elseif (isset($_COOKIE['email']) || isset($_COOKIE['password'])) {
echo "hello $name";
}
}
}
That's pretty much the jist of it..
The attempt at combining the two is located at:
http://protein.guru/testlogin.phtml
the separate scripts are located at:
http://protein.guru/signin.phtml
http://protein.guru/login.php
My only 2 questions are:
Is it possible to do so with my current format using php?
If it is not possible with the format I'm using, does anyone have an idea of a format that would work?
I am using the email: tester3651#outlook.com
Password is: meatloaf
Use <button></button> with the same name and different value attribute. Your PHP would be something like:
<?php
$submit = $_POST['submitButtonName'];
if ($submit == 'value1') {
// do stuff here
} else if ($submit == 'value2') {
// do other stuff here.
};
You may use a switch case, you may use more ifs. Although I can't see the benefit of using the same PHP script to different forms. If they have different fields and values and have a whole differente behave, there should be two scripts, one for each form.
Basically I have several big forms (lot of fields submitted) that need to be processed, which are very similar but may differ by one or two fields. Firstly all fields get escaped and assigned to a variable of their original name (thus $_POST['f_name'] will be $f_name).
Then I need to validate the data, things like certain obligatory fields must be present, certain fields much match (confirming password/email), certain fields must pass regex check. I do this via a long if/else statement, where each failure has it's own error message.
Now of course I would like to avoid this repetition of the clumsy code, and replace it with some looping function, which will be easier to edit and maintain.
However this poses a bit of a problem, especially performing the checks and assigning individual error messages.
I would be keen to hear suggestions as how would you approach developing such validation/error reporting function.
Here is a short version of what the code looks like:
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
$password_re = mysqli_real_escape_string($mysqli, $_POST['password_re']);
if ($name == '') :
$data = "Please enter name";
elseif ($password != $password_re) :
$data = "Passwords don't match";
endif;
First off I would make a function to clean your post array.
$clean_post = sanitize($_POST);
function sanitize($input) {
if (is_array($input)) {
foreach($input as $var=>$val) {
$output[$var] = sanitize($val);
}
}
else {
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
}
$input = cleanInput($input);
$output = mysql_real_escape_string($input);
}
return $output;
}
Next I would add divs with the same name as the field and set error variable within the $data array and remove the ifs in between them, personally I hate being spoon fed my form errors.
if ($name == '')
$data['name'] = "Please enter name";
if ($password != $password_re)
$data['password] = "Passwords don't match";
Finally, I would set the content of the divs to the $data array value.
<div><?=$data[name];?></div>
<input type="text" name="name" value="<?=$clean_post[name];?>">
<div><?=$data[password];?></div>
<input type="password" name="password" value="<?=$clean_post[password];?>">
<input type="password" name="password_re" value="<?=$clean_post[password_re];?>">
Hope this helps
I'm not sure that there's one cut-and-dried approach to this problem. Here's how my company has addressed this problem:
1) Front side validation. Yes, can be bypassed. However, if you're only using it as the first line of defense it's a great solution (and acceptable to some of my biggest clients including an international banking group) I love the simplicity of Cedric Dugas' inline validation script because it's basically just a few extra characters per field. Another HUGE benefit to the inline validation--it allows us to use one centralized alert area for server-side validation errors along with a simple alert trigger via css on individual elements, while the majority are caught inline and alerted which is FAR more user friendly.
2) A class that deals with "stuff" We refer to it as the "garbage in, garbage out" It takes an array of post data, sets fields based on element names, and deals accordingly. This includes data sanitizing, validations, etc. The problem with validations is that unless you have generic types data to validate, you can get into a lot of specifics which can really gum up code in a hurry. Also, this can make you actually have to do MORE work on the front end because your field names have to line up accordingly. In our case, we deal with external webform responses from clients a lot who don't necessarily appreciate the need for standardized naming of fields, and that can get to be a headache.
3) "Chunking" sections. On huge form scenarios, we've resorted to "chunking" submits in phases via Ajax to minimize the damage to the server done in one big submit. So, user updates profile information, submit happens. User does background info section, update happens...etc. It's not right for all situations, but is some it can work well...and it allows progressive validation as you move from start to finish. I certainly wouldn't ever recommend this approach for each individual question, though.
4) "Forced Sanitation" Sounds evil, huh? In cases such as zip codes, addresses, etc you can simply fix information for the client. Rather than barking about a missing Zip Code, you can get it automatically, correct 100% of the time. That's the beauty of Google and the USPS--they're free and smarter than the average user.
I'd say it's better to do this on the client side using a javascript form validator, before anything gets submitted. Do a search for javascript form validation. It'll save you a page load and force your users to correct errors before even submitting. Here's a simple example of one way, taken from the first google hit for "javascript form validation":
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script language="javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
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/