I am validating an HTML Form with PHP. All of my code is fine, except the message field. If I put something in the message field and the other fields are displaying errors, it still submits. But, if I put something into the other fields and the other fields have errors, it won't submit, which is correct. I suspect it has something to do with the last if-else of my code. Thank you in advance.
contact.php
<?php
include 'includes/config.php';
$errors = FALSE;
$displayErrors = NULL;
if (isset($_POST['submit'])) {
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//Connect to MYSQL Database server
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Could not connect to MYSQL Database.");
$result = mysql_select_db(DB_NAME, $connect) or die("Could not connect to MYSQL table.");
//Clean Data to prevent malicous injections
mysql_real_escape_string(strip_tags(stripcslashes(trim($first))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($last))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($email))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($subject))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($message))));
if (empty($first)) {
$errors = TRUE;
$displayErrors .= 'First name is invalid.<br/>';
}
if (empty($last)) {
$errors = TRUE;
$displayErrors .= 'Last name is invalid.<br/>';
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors = TRUE;
$displayErrors .= 'Email is invalid.<br/>';
}
if (empty($subject)) {
$errors = TRUE;
$displayErrors .= 'Subject is invalid.<br/>';
}
if (empty($message)) {
$errors = TRUE;
$displayErrors .= 'Message is invalid.<br/>';
} else {
$errors = FALSE;
//Database insertion goes here
echo 'Form submission successful. Thank you ' . $first . '.';
}
}
?>
Basically you are saying, if the message is not empty then $errors=FALSE, but you don't take into account all the other fields.
I'd suggest putting the errors in an array like:
$errors['email'] = true;
Then checking that array at the end using a foreach
Try turning that else into
if($errors == FALSE) {//just corrected the equality operator
//Database insertion goes here
echo 'Form submission successful. Thank you ' . $first . '.'
}
Before all of those ifs, you should put $errors = FALSE. Then instead of the else at the end of your code, you can put if(!$errors){ //database insertion here }
Make all your ifs else ifs
that way your last else will not mess up your validation.
First off, Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I've tidied your logic, instead of using $error=true ect you should build an error array (containing your error text) and then check if thats empty at the end, I also cleaned up the magic quotes problem it seems your having, and the horrid multiple mysql_real_escape_string's, hope it helps
contact.php
<?php
include 'includes/config.php';
//Connect to MYSQL Database server
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Could not connect to MYSQL Database.");
$result = mysql_select_db(DB_NAME, $connect) or die("Could not connect to MYSQL table.");
$errors = array();
if ($_SERVER['REQUEST_METHOD']=='POST') {
function clean(&$value){
if (get_magic_quotes_gpc()){
$value = mysql_real_escape_string(strip_tags(trim($value)));
}else{
$value = mysql_real_escape_string(trim($value));
}
}
array_walk($_POST,'clean');
if (empty($_POST['first'])) {
$errors['first']= 'First name is invalid.<br/>';
}else{
$first = $_POST['first'];
}
if (empty($_POST['last'])) {
$errors['last']= 'Last name is invalid<br/>';
}else{
$last = $_POST['last'];
}
if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Email is invalid.<br/>';
}else{
$email = $_POST['email'];
}
if (empty($_POST['subject'])) {
$errors['subject']= 'Subject is invalid.<br/>';
}else{
$subject = $_POST['subject'];
}
if (empty($_POST['message'])) {
$errors['message']= 'Message is invalid.<br/>';
}else{
$message = $_POST['messsage'];
}
if(empty($errors)){
//Database insertion goes here
echo 'Form submission successful. Thank you ' . htmlentities($first) . '.';
}else{
//Errors, so your have $errors['name'] ect to output
//so somthing like:
echo (isset($errors['name'])?$errors['name']:null);
}
}
?>
You should also perhaps add a condition that the value is a min certain length, with strlen($_POST['first']) > 2 ect.
Related
I have a form which when submitted, checks this query ->
if(isset($_POST['update']) && !empty($_POST['name']) && !empty($_POST['reg_name']))
I want to echo a message "Please fill up all the required fields." if the required fields are not filled up.
In short, it should highlight the field name which is not filled up.
The Full Code:
include ('database/abcd.php');
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['update']))
{
$error = array();
if(empty($_POST['name']))
$error[] = 'Please fill name field';
if(empty($_POST['reg_name']))
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1)
{
$name = $_POST['name'];
$reg_name = $_POST['reg_name'];
$established = $_POST['established'];
$industry = $_POST['industry'];
$about = $_POST['about'];
$website = $_POST['website'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$facebook = $_POST['facebook'];
$wiki = $_POST['wiki'];
$twitter = $_POST['twitter'];
$google = $_POST['google'];
$member_username = $_SESSION['username'];
$process="INSERT INTO notifications (member_username, process, icon, class) VALUES ('$_POST[member_username]','$_POST[process]','$_POST[icon]','$_POST[class]')";
if (!mysqli_query($con,$process))
{
die('Error: ' . mysqli_error($con));
}
$sql = "UPDATE `company_meta` SET `name` = '$name', reg_name = '$reg_name', wiki = '$wiki', established = '$established', industry = '$industry', about = '$about', website = '$website', mail = '$mail', phone = '$phone', address = '$address', city = '$city', facebook = '$facebook', twitter = '$twitter', google = '$google' WHERE `member_username` = '$member_username'";
if ($con->query($sql))
{
header('Location: edit.php');
}
}
else
{
$errors = implode(',' $error);
echo $errors;
}
$con->close();
}
I think what you are pass in name or reg_name is check first .may be name or reg_name can content white space so that it not showing message otherwise above code is working correctly..
if(isset($_POST['update'])) // This first check whether it is an update call
{
$error = array(); // Here we initialize an array so that we can put the messages in it.
if(empty($_POST['name'])) // If the name field is empty, push a message in $error array.
$error[] = 'Please fill name field';
if(empty($_POST['reg_name'])) // Same as above field
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1) // Now this checks if the $error array has no value. If it has value it means that either or both of the above fields are empty and the else block will be executed.
{
// Submit your form
}
else
{
$errors = implode(',' $error);
echo $errors;
}
}
else
{
// Update not triggered.
}
I m trying a contact form in php where the details as to get stored in the database.If i dont enter any values it displays error msg but it gets stored in the database. How can I validate form when error message displays the data should not be entered in database.
Here is the code
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$name="";
$email="";
$batch="";
$mobile="";
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['batch'])) {
$batch = $_POST['batch'];
} else {
$error .= "You didn't type batch. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (!empty($_POST['mobile'])) {
$mobile = $_POST['mobile'];
} else {
$error .= "You didn't type your Mobile Number. <br />";
}
if (empty($error)) {
$success = "<b>Thank you! Your message has been sent!</b>";
}
}
?>
<div id="contactForm">
<?php
if (!empty($error)) {
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
mysql_query("INSERT INTO contact (name,batch,email,mobile)
VALUES('$name','$batch','$email','$mobile') ") or die(mysql_error());
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
?>
This is opposite of what it should be
if (!empty($error)) {
^
// your database stuff here
}
You should run that query when the error is empty, and not when its not empty.
if (empty($error)) {
// now save to database
}
Also go through How can I prevent SQL injection in PHP?
Check the condition on which you are inserting the data in the database. You are checking if (!empty($error)) which should denote that there is an error. Also since $error is a string, I would recommend you to check the values as if(trim($error) != "") rather than using empty()
you should use else if to check each condition..
if(isset($POST['submit'])){
if(empty($_POST['email'])){
$error[] = "email is required";
}
elseif(empty($_POST['name'])){
$error[]= "name is required;";
}
...
else{
$email = $_POST['email'];
$name = $_POST['name'];
// do all the stuff here
}
}
// also correct !empty ()
mysql_query(" INSERT INTO contact (`name`,`batch`,`email`,`mobile`)
VALUES('".$name."','".$batch."','".$email."','".$mobile."');
You need to concatenate the strings. If you put $email in quotes, it will be considered a string and not a variable.
PHP Code:
$dom = new DOMDocument;
$headtitle = "Register";
$errors = array();
if(isset($_POST['register'])){
$username = preg_replace('/[^A-Za-z]/', '', $_POST['username']);
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$c_password = $_POST['c_password'];
$birthday = $_POST['birthday'];
$country = $_POST['country'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$level = $_POST['level'];
$date = $_POST['date'];
if(file_exists('users/' . $username . '.xml')){
$errors[] = ' Username already exists';
}
if($username == ''){
$errors[] = ' Username is missing. Try again.';
}
if($name == ''){
$errors[] = ' Name is missing. Try again.';
}
if($lastname == ''){
$errors[] = ' Lastname is missing. Try again.';
}
if($country == ''){
$errors[] = ' Country is missing. Try again.';
}
if($gender == ''){
$errors[] = ' Gender is missing. Try again.';
}
if($age == ''){
$errors[] = ' Age is missing. Try again.';
}
if($email == ''){
$errors[] = ' Email is missing. Try again.';
}
if($password == '' || $c_password == ''){
$errors[] = ' Passwords are missing. Try again.';
}
if($password != $c_password){
$errors[] = ' Passwords do not match';
}
if(count($errors) == 0){
$xml = new SimpleXMLElement('<user></user>');
$xml->addChild('name', ($name));
$xml->addChild('lastname', ($lastname));
$xml->addChild('password', md5($password));
$xml->addChild('birthday', $birthday);
$xml->addChild('country', $country);
$xml->addChild('gender', $gender);
$xml->addChild('age', $age);
$xml->addChild('email', $email);
$xml->addChild('level', $level);
$xml->addChild('date', $date);
$xml->asXML('users/' . $username . '.xml');
header('Location: index.php');
die;
}
}
Javascript Code:
function vaildate() {
if (document.getElementById('username').value.length <= 4) {
document.getElementById('errors').innerHTML = "Username must me more than 4 words <br />";
return false;
}
return true;
}
Now my problem is, that when I click submit button (that contains name="login" and onclick="vaildate();") he excute only php errors and ignores javascript errors (assuming that id="username" has less than 4 words).
My question is how can I make Javascript & PHP errors work? not only PHP and the system ignores Javascript.
Thank you all..
EDIT:
Also i got this code to echo PHP errors
if(count($errors) > 0){
echo '<font color="red"><ul>';
foreach($errors as $e){
echo '<li>' . $e . '</li>';
}
echo '</ul></font>';
}
Try this:
onclick="return vaildate();"
You need to return the validate function (return the true or false), not just call it.
Your Javascript and PHP you are showing looks fine. What we don't have is the actual markup of the login page. My suspicion is that your markup is not consistent with the code you have in your Javascript.
If you could also try and explain more specifically what you mean by
My question is how can I make Javascript & PHP errors work? not only PHP and the system ignores Javascript.
Have you used a Javascript debugger to see if part your Javascript (maybe elsewhere on the page) is erroring?
I have created a simple form which has some required fields which if not completed will pass back an error to the user to inform them that the field is require.
As there are multiple field which is checks it can output multiple error messages.
I want to know how I can define an area on my form where these errors are displayed as at the moment these error simply display at the bottom of the form, which you can't see unless you scroll down the page.
Can I define where my error are displayed.
Here is the error checking code: EDIT
Old code was here
People in the past have suggested I make a loop to check for errors one at a time but I am novice at php so not sure how to do this.
$errors = '';
if(empty($_POST['studentName']))
{
$errors .= "You did not enter the student name<br/>";
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
$errors .="You did not select a tutor<br/>";
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
$errors .="You did not enter a procedure<br/>";
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
$errors .="You did not enter a grade<br/>";
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
$errors .="You did not enter a reflection<br/>";
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
$errors .="You must enter a reasan why you ticked the alert box";
}
//Code to check the password field is completed and correct
if (empty($_POST['password']))
{
$errors .="You did not enter you password";
}
if (!empty($_POST['password']))
{
//==========================================
// ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$masterpass = $_POST['password'];
$masterpass = htmlspecialchars($masterpass);
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$user_name = "username";
$pass_word = "password";
$database = "name of database";
$server = "server";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$masterpass = quote_smart($masterpass, $db_handle);
$SQL = "SELECT * FROM masterpass WHERE password = $masterpass";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($result) {
if ($num_rows > 0) {
echo "";
}
else {
$errors .= "Password was not recognised";
exit();
}
}
mysql_close($db_handle);
}
}
if(!empty($errors))
{
echo '<div class="errors">' . $errors . '</div>';
exit();
}
}
You could do something like
$errors = '';
if(empty($_POST['studentName']))
{
$errors .= "You did not enter the student name<br />";
}
if(empty($_POST['tutorName'] ))
{
$errors .= "You did not select a tutor name.<br />";
}
// etc.
and then above your <form> have
if (!empty($errors))
{
echo '<div class="errors">' . $errors . '</div>';
}
styling .errors with CSS so it'll stand out more. If $errors is blank higher up in your application logic, you can then perform the usual add / update to a database and redirect to a success page.
echo()ing your errors is what's adding them to the bottom. As the previous answer suggested, assigning them to a string and printing that in a defined div (if it's not empty) is how the pros do it!
Defining errors as an array also works, and allows you a bit more fine-grained control over the error process.
$errors = array();
if(empty($_POST['studentName']))
$errors[] = "You did not enter the student name";
if(empty($_POST['tutorName'] ))
$errors[] = "You did not select a tutor name.";
//etc...
//At the top of your page.
if (sizeof($errors)>0) {
echo "<div class='errordiv'>";
echo "<ul>";
foreach ($errors as $err) {
echo "<li>".$err."</li>"; //or whatever format you want!
}
echo "</ul></div>";
}
You can also pass the error array around as a parameter to other functions, log them, etc.
$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';
$yourname='';
$email='';
$email2='';
$password='';
$password2='';
$country='';
if (isset($_POST['Registerme']))
{
$_POST['yourname']=$yourname;
$_POST['email']=$email;
$_POST['email2']=$email2;
$_POST['password']=$password;
$_POST['password2']=$password2;
$_POST['country']=$country;
if($yourname==''){
$error1='name required';
}
if($email==''){
$error2='email required';
}
if($email2==''){
$error3='required field';
}
if($password==''){
$error4='password required';
}
if($password2==''){
$error5='required field';
}
if($country==''){
$error6='country required';
}
if(empty($error1) && empty($error2) && empty($error3) && empty($error4) && empty($error5) && empty($error6))
{echo 'mysql query goes here and add the user to database';}
}///main one
else {$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';}
this is a registration validation script. in my registration form there are two email and password filelds.second fields are for confirmation.i want to check weather user typed same information in that both field.if i want to do that in this script should i use another if statement? or i should use else if? i am confused about that step...
Some comments:
You MUST sanitize input! Take a look at best method for sanitizing user input with php.
Your assignments: Instead of "$_POST['yourname']=$yourname;" it should be "$yourname=$_POST['yourname'];".
You're using a lot of variables for error control, and after that if all went well you simply forget the error messages in the last else block. Use some kind of array for error strings, and use it!
Are you sure you aren't validating usernames/passwords to not contain spaces or weird characters, or emails to be valid?
Some sample code...:
// Simple sanitize function, complete it
function sanitize_input ($inputstr) {
return trim(mysql_real_escape_string($inputstr));
}
if (isset ($_POST['Registerme']) {
// array of error messages to report
$error_messages = array();
$isvalid = true;
// Assignment
$yourname = sanitize_input ($_POST['yourname']);
$email = sanitize_input ($_POST['email']);
$email2 = sanitize_input ($_POST['email2']);
$password = sanitize_input ($_POST['password']);
$password2 = sanitize_input ($_POST['password2']);
$country = sanitize_input ($_POST['country']);
// Validation
if (empty ($yourname)) {
$error_messages[] = "You must provide an username";
}
if (empty ($password)) {
$error_messages[] = "You must provide a password.";
}
elseif ($password !== $password2) {
$error_messages[] = "Passwords do not match.";
}
// Same for email, you caught the idea
// Finally, execute mysql code if all ok
if (empty($error_messages)) {
// Execute mysql code
isvalid = true;
}
}
// After form processing, use isvalid which is false if there are errors
// and the error_messages array to report errors
add additional conditions to your second if statement.
e.g.
if($email=='' || $email != $email2){
...
Just add simple checks. I wouldn't combine the check with the general password check - as I can imagine you would like to tell the user what went wrong exactly.
if ($password1 !== $password2) {
// Add an specific error saying the passwords do not match.
}
I would replace the user of loose errors to an array like:
$aErrors = array();
if ($password1 !== $password2) {
$aErrors[] = 'Another specific error!';
}
if (empty($password1) || empty($password2)) {
$aErrors[] = 'Another specific error';
}
if (empty($aErrors)) {
// Process the form!
}
There are lots of issues with your code.
1. You are assinging $_POST['key'] = $somevalue, while I think you mean $somevar = $_POST['key']
2. Use an array for all error messages as it'll make your life a bit easier ..
3. To compare password use something like
if ($password1 !== $password2) {
}
so .....
$errors = array();
so you'd check something like ..
if ($password1 !== $password2) {
$errors[] = 'Password dont match';
}
if(count($errors) > 0) { //if there are errors
foreach($errors as $err) {
echo $err.' <br />';
}
} else {
// whatever you want to do if no error
}
I'll also suggest to sanitise the $_POST values before you use them in your queries.
I hope it helps.
I think you mean to do this:
$yourname = $_POST['yourname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$country = $_POST['country'];
Second this make use of an errors array:
$errors = array();
Third use nested ifs(just a suggestion)
if (!empty($_POST['password1'])) {
if ($_POST['password1'] != $_POST['password2']) {
$errors[] = '<font color="red">The 2 passwords you have entered do not match.</font>';
} else {
$password = $_POST['password1'];
}
} else {
$errors[] = '<font color="red">Please provide a password.</font>';
}