ive written a php function that displays a random equation. if the correct answer is not provided, the submission fails. the equation is like so:
[ random digit or text number ] [ randomly selects +,-,x ] [ random digit or text number ]= ?
so you might see:
8+2=?, or seven - 4 = ?, etc
ive tested this manually and it seems to work beautifully. i cannot get around answering the CAPTCHA correctly. yet something or someone IS posting spam despite this CAPTCHA. so my question is, are there programs out there that can solve this problem?
here is my form:
<form action="scripts/handler_post.php" method="post" id="gb_form">
<h3>Leave us a comment:</h3><br />
<div id="form_msg"><?php echo $msg; ?></div>
<input type="text" name="name" value="Your Name" />
<textarea name="message">Your Message</textarea>
<?php include('includes/bmw_captcha.php'); ?>
<div style="color:red; font-size:90%;">*What does <?php echo $array_num1[1] . " " . $array_calculation[0] . " " . $array_num2[1] . " = "; ?>
<input type='text' maxlength='2' name='captcha' style="color:#640513; width:25px;" />?</div>
<div><span style="font:italic 90% Arial; color:#666;">(For security purposes, please answer this CAPTCHA problem.)</span></div>
<input type="hidden" name="captcha_answer" value="<?php echo $array_calculation[1]; ?>" />
<input type="submit" name="submit_button" value="Post" />
</form>
here is the script that handles the form:
// submitted values
$name = clean_string( $_POST['name'] );
$message = clean_string( $_POST['message'] );
$captcha = clean_string( $_POST['captcha'] );
$captcha_ans= clean_string( $_POST['captcha_answer'] );
// check if name var is empty or contains digits
if( empty($name) || (strcspn( $name, '0123456789' ) != strlen( $name )) )
{ header( 'Location: /guestbook.php?msg=n' ); }
else if( empty($message) )
{ header( 'Location: /guestbook.php?msg=m' ); }
else if( empty($captcha) || $captcha != $captcha_ans )
{ header( 'Location: /guestbook.php?msg=cap' ); }
else
{
$query = "
INSERT INTO $table_posts ( id, name, message, timestamp )
VALUES( 0, \"$name\", \"$message\", now() )
";
$result = $db_connect->query( $query ); // execute the query
if( $result )
{
header('Location: ../guestbook.php?msg=1');
}
else
header('Location: ../guestbook.php?msg=2');
}
You should store the answer to the captcha in a session variable instead. Sending it in clear text through the form makes it possible for a robot to just set the field to whatever value it wants. Bots are usually setting all unknown fields to some string, like ijhsg87dfb34 so if it sets both the captcha and the captcha_answer field to the same value it will succeed!
A very simple approach is to use a hidden field, and in the script that handles the POST you check if that field was filled in, if it was then it was a BOT etc as a normal user would never see that field but BOTs etc just blindly fill in every field.
You can try non-captcha secure form. Check this
http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs
Related
I need help with a contact form for my website. I'll begin by explaining how my form is set up. My website has a single page (index.php) with three sections. The last one is "Contact Us" and it has a form where users are supposed to input their name, email address and a message.
My contact form worked ok, but it needed some security against spam bots. So I decided to add a simple anti-spam question, e.g., "2 + 2." I wanted this question to be different each time and that's what's giving me problems. I'd really appreciate if you could point me in the right direction to solve this!
Here's the code I'm using. I'll explain it below.
<a name="contact"><h2>Contact Us</h2></a>
<?php
$operation = mt_rand(0, 2);
switch ($operation) {
case 0:
$r1 = mt_rand(0, 50);
$r2 = mt_rand(0, 50);
$r3 = $r1 + $r2;
$query = "How much is $r1 + $r2?";
break;
case 1:
$r1 = mt_rand(0, 50);
do {
$r2 = mt_rand(0, 50);
} while ($r2 >= $r1);
$r3 = $r1 - $r2;
$query = "How much is $r1 - $r2?";
break;
case 2:
$r1 = mt_rand(0, 10);
$r2 = mt_rand(0, 10);
$r3 = $r1 * $r2;
$query = "How much is $r1 × $r2?";
break;
}
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["human"]) && isset($_POST["message"])) {
$name = spam_check('name');
$from = spam_check('email');
$subject = empty($_POST['subject']) ? "Contact Form Message" : spam_check('subject');
$human = spam_check('human');
$message = "<!DOCTYPE HTML><html><body><p>";
$message .= "<strong>Name:</strong> " . $name . "<br>";
$message .= "<strong>Email:</strong> " . $from . "</p>";
$message .= "<p><strong>Message:</strong><br>" . spam_check('message') . "</p>";
$message .= "</body></html>";
$to = "hello#example.com";
$headers = "From: Me<hello#example.com>\nReply-To:" . $name . "<" . $from . ">\n";
$headers .= "Mime-Version: 1.0\n";
$headers .= "Content-Type: text/html; charset=UTF-8";
if ($_POST['submit']) {
if (!strcmp($human, $_SESSION['human'])) {
if (mail($to, $subject, $message, $headers)) {
echo "<p class=\"success\">Thanks for contacting us.</p>";
} else {
echo "<p class=\"failure\">Something went wrong, please try again!</p>";
}
unset($_SESSION['query']);
unset($_SESSION['human']);
} else {
echo "<p class=\"warning\">You did not answer our anti-spam question. Do you need help?</p>";
}
} else {
echo "<p class=\"failure\">Something went wrong, please try again!</p>";
}
}
if (!isset($_SESSION['human'])) {
$_SESSION['query'] = $query;
$_SESSION['human'] = "$r3";
} ?>
<form action="#contact" method="post">
<input type="text" name="name" placeholder="Name" title="Name" required>
<input type="email" name="email" placeholder="Email" title="Email" required>
<input type="text" name="subject" placeholder="Subject" title="Subject">
<input type="text" name="human" placeholder="<?php echo $query; ?>" title="<?php echo $query; ?>" required>
<textarea name="message" placeholder="Write your message here…" title="Message" rows="10" cols="40" required></textarea>
<input type="submit" name="submit" value="Send">
</form>
Here's the explanation of what I'm trying to achieve with the code above: first I generate one random number to decide if the question's going to be an addition, a subtraction or a multiplication. If I get:
0, I generate two random numbers below 50 and add them.
1, I generate two random numbers below 50 and subtract them (note: second number must not be greater than the first one to prevent negative results).
2, I generate two random numbers below 10 and multiply them.
The question's result is stored in $r3 and the question itself is stored in $query.
Next, I check if the user has submitted the form. If they have, I extract their input using a function named spam_check. spam_check is supposed to stop header injection. It seems to work, although I haven't tested it thoroughly. Once I have extracted the values of each field, I start to construct the email's body and the headers. This works too. Hold on we're about to get to the problem.
The next step is to check if the user's answer to the anti-spam question ($human) matches the value of $r3. This is the part that I can't get to work. I used to have a simple check: $human == $r3, but I soon realized it wasn't going to work because once you submit the form, the page reloads and $r3 becomes a new number. So I decided that maybe sessions were the way to go out.
In the last lines, the value of $r3 is stored in $_SESSION['human'] if $_SESSION['human'] is unset (e.g., the first time the page is loaded). To determine if the user answered correctly I use !strcmp($human, $_SESSION['human']), but it doesn't work because $_SESSION['human'] does not store the value!
It looks like once you submit the form, the session is somehow lost and the stored values are reset. How can I store and preserve $r3's value?
I've already checked if sessions are enabled in my server and I've also found the temporary session files (e.g., query|s:20:"How much is 19 - 12?";human|s:1:"7";), so I don't where else to look for solutions.
You probably need to run
session_start();
in the beginning of your code. See http://www.php.net/session_start for more info. Notice that you should put session_start() before any other output to the browser.
I am creating an admin page, where the admin person can create users accounts for people. The idea is, that once the form is completed, when clicking 'Submit' an email must be sent to the user (containing the ID and name of account selected). In the same action, the form must also first be validated and if there are any errors with the validation the data should not be submitted to the database. None of this is happening though and I cannot figure out why.
The email is not being sent,
the data is inserted in the database even if there are errors and upon loading the page,
errors are displayed for all form fields even though the submit button have not been clicked.
Any help, advice or links to possible sources/tutorials would be greatly appreciated.
Below is my code: (Note that I am only working in PHP, HTML and using a MYSQL database)
<html>
<head>
<title>
User Registration
</title>
<?PHP
include_once 'includes\functions.php';
connect();
error_reporting(E_ERROR | E_PARSE);
//Assign variables
$accounttype=mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
//Validating form(part1)
$error='';
//Connect to database
$SQL=
"INSERT INTO student
(
sname,fname,email, address, contact_flag
)
VALUES
(
'$sname', '$fname', '$email', '$address', '$contact_flag'
)
";
if (!mysql_query($SQL))
{
print'Error: '.mysql_error();
}
mysql_close($db_handle);
//Validate form(part 2)
if (isset($_POST['sname'], $_POST['fname'],$_POST['email'],$_POST['address']));
{
$errors=array();
$accounttype= mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
// form validation
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)===FALSE)
{
$errors[]='Please insert your valid email address';
}
if(strlen(mysql_real_escape_string($address))<8)
{
$errors[]='Please insert your postal address';
}
echo'<pre>';
print_r($errors);
echo'</pre>';
}
//confirmation email
// Subject of confirmation email.
$conf_subject = 'Registration confirmed';
// Who should the confirmation email be from?
$conf_sender = 'PHP Project <my#email.com>';
$msg = $_POST['fname'] . ",\n\nThank you for registering. \n\n You registered for account:".$accounttype."\n\n Your account number:".mysql_insert_id;
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
?>
</head>
<body>
</br>
<form name ="form0" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<b>Select the course you wish to register for:</b></br>
<select name="accounttype">
<?PHP query() ?>
</select>
<?PHP close() ?>
</form>
<form name ="form1" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<Input type ="" Value = "Surname" Name = "sname"></br>
<Input type ="" Value = "First name" Name = "fname"></br>
<b>Email:</b> <Input type ="" Value = "" Name = "email"></br>
<b>Address:</b> </br>
<textarea rows="4" cols="20" Name="address">Please provide your postal address here </textarea></br>
<b>Tick to receive confinmation email:</b> <Input type ="checkbox" Value = "1" Name = "contact_flag"></br>
<Input type = "Submit" Value="Submit">
</form>
</body>
</html>
<?PHP
if(isset($_POST['submit']))
{
include_once 'includes\functions.php';
connect();
// your rest of the code
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
}
?>
and keep this code out of the <html> tag but before it
and if you want to stick to PHP only then one error i can see is
that you have kept the **validation code below the `INSERT`**
query which means that the insert query will be executed first which will store the data in the database first and then it will go for the validation...so keep your validation code above the INSERT statement..
and second thing use exit() method after vaidating every field if it gives you error...it will stop executing rest of the php code if any field gives the error during validation....and so it will also prevent the data from storing into the database if it finds exit method whenever an error is found eg
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
echo '//whatever you want to echo';
exit();
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
echo '//whatever you want to echo';
exit();
}
At first, your query gets executed before you validate your form.
Move your SQL after your
echo'<pre>';
print_r($errors);
echo'</pre>';
and surround it with
if(!$errors){}
This will prevent your query from being executed if there are any errors.
(You can also delete your first assignement of your variables)
Concerning your email problem, test your connection with a simple message
mail('your#email.com', 'subject', 'message');
If you get any error, probably your mailserver isn't set up right
I am using Screets Wordpress Sessions plugin and it works really well. The problem I am having is this, I am going to manage my site users out of wordpress through a different table and etc. I have my signup form working, were it sends out confirmation emails to stop spam. The issue I am having is that my simple form:
mysql_connect("localhost", "%username%", "%password%") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("%database%") or die(mysql_error()); // Select registration database.
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password']) AND isset($_POST['name']) && !empty($_POST['name'])){
$username = mysql_escape_string($_POST['name']);
$password = mysql_escape_string(md5($_POST['password']));
$search = mysql_query("SELECT username, password, active FROM %table% WHERE username='".$username."' AND password='".$password."' AND active='1'") or die(mysql_error());
$match = mysql_num_rows($search);
if($match = 1){
$msg = 'Login Complete! Thanks';
//$email = $row['EmailAddress'];
//;
//$_SESSION['EmailAddress'] = $email;
//$_SESSION['LoggedIn'] = 1;
$session->set_userdata( 'username', $username);
header ("Location: /");
}else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
}
?>
<!-- stop PHP Code -->
<!-- title and description -->
<h2>Login Form</h2>
<p>Please enter your name and password to login</p>
<?php
if(isset($msg)){ // Check if $msg is not empty
echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and add a div around it with the class statusmsg
} ?>
<!-- start sign up form -->
<form action="" method="post">
<label for="name">Username:</label>
<input type="text" name="name" value="" />
<label for="password">Password:</label>
<input type="password" name="password" value="" />
<input type="submit" class="submit_button" value="login" />
</form>
auto redirects to my wordpress login which is not what I want. I have been told before to use wp_users but I really don't want to use that or a plugin. Any ideas to get it to work the way I need to?
EDIT: To better clarify the question, anyone who clicks submit is redirected to wp-login.php. The page is not even following my SQL connect to check and actually create a session. Any ideas?
The better way is using Ajax to send and sava your data. First, include these codes below into your functions.php:
/**
* User Log in
*/
function sc_login( $params ){
global $wpdb;
// You can check user here
$sql = $wpdb->prepare(
'
SELECT COUNT(*) FROM ' . $wpdb->prefix . ' users
WHERE `email` = %d
AND `password` = %s
',
$params['user_login'], $params['user_password']
);
$auth = $wpdb->get_var( $sql );
if( $auth ) {
// Log in system
} else {
// Username or password is wrong
}
}
/**
* Ajax Submit
*/
function sc_ajax_callback() {
// run function
$response = call_user_func($_POST['func'], $_POST);
// response output
header( "Content-Type: application/json" );
echo json_encode($response);
exit;
}
// Ajax Requests
add_action( 'wp_ajax_nopriv_sc_ajax_callback', 'sc_ajax_callback' );
add_action( 'wp_ajax_sc_ajax_callback', 'sc_ajax_callback' );
Create an Ajax.js file into your theme and add these codes:
(function ( $ ) {
jQuery(document).ready(function() {
/**
* Log in
*/
$('#sc_login_form').submit(function() {
jQuery.ajax({
type: 'POST',
url: sc_ajax.ajaxurl,
data: $('#sc_login_form').serialize(),
dataType: 'json',
success: function(response, textStatus) {
// Show errors?
if( response.errors ){
// YOU CAN SHOW ERRORS HERE IF YOU WANT
// for instance, "Email is required!"
// successful log in
} else {
// refresh page (HERE IS THE POINT)
window.location.href = sc_ajax.REDIRECT_URL;
}
console.log(response);
}
});
return false;
});
});
}( jQuery ));
Now we need to localize Ajax script. Open header.php and add these codes before wp_head(); function. Don't forget to change REDIRECT_URL variable below:
// insert jquery
wp_enqueue_script( 'jquery' );
// ajax requests
wp_enqueue_script( 'sc-ajax-request', get_template_directory_uri() . '/Ajax.js', array( 'jquery' ) );
// prepare your ajax custom vars
$ajax_vars = array(
'REDIRECT_URL' => '', // (!) CHANGE THIS WITH URL WHERE YOU WANT TO GO
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_localize_script( 'sc-ajax-request', 'sc_ajax', $ajax_vars );
And last step is edit your form like this:
<form id="sc_login_form">
<input type="hidden" name="action" value="sc_ajax_callback" />
<input type="hidden" name="func" value="sc_login" />
Email:
<input type="text" name="user_login" />
Password:
<input type="password" name="user_password"/>
<input type="submit" value="Log in" />
</form>
I hope this helps.
Ah yes. WordPress's Rewrite API is stepping on you. When you submit your form, the script attempts to post back to itself. WordPress takes http://your-site.com/login and rewrites
it to http://your-site.com/wp-login.php.
Here's how to fix it.
Create a page in WordPress, name it login, then assign the custom page template to it you'll create in this next step.
Now you'll need to create a custom page template, place it in your currently active theme folder, and put the following code in it:
<?php
/*
* Template Name: Login
*/
// Put the code for your login here.
?>
Finally, add this next line to your theme's functions.php:
add_rewrite_rule( '^login/?$', 'index.php?page_name=$matches[1]', 'top' );
That should do the trick nicely. :)
I have a working example of a form here. I need to use Javascript of Jquery form validation to verify that the user has inputted his/her own data. So far I have tried to check for values, but obviously this didn't work, because the inputs and textarea already have a default value, and so the user can submit straight away without filling in anything.
Any help would be much appreciated.
Thanks in advance!
EDIT
I am using this php to send the submitted data to an email address:
<?php
$name = $_POST['name'];
if ($name=="") {
$name="Nothing was returned for this part of the form.";
}
$email = $_POST['email'];
if ($email=="") {
$email="Nothing was returned for this part of the form.";
}
$subject = $_POST['subject'];
if ($subject=="") {
$subject="Nothing was returned for this part of the form.";
}
$comments = $_POST['comments'];
if ($comments=="") {
$comments="Nothing was returned for this part of the form.";
}
$theMessage7="<b>Results from the form at www.site.co.uk/contact.html</b><br /><br />" . "Name: " . $name . "<br />" . "Email: " . $email . "<br />" . "Subject: " . $subject . "<br />" . "Message: " . $comments . "<br />";
$theEmail7="mail#mail.com";
$theSubject7="New form submission";
$theHeaders7="MIME-Version: 1.0
Content-type: text/html; charset=iso-8859-1
From: form#bikeinc.co.uk
Subject: New form submission";
$theErrorFile7="www.site.co.uk/12345";
$theThanxFile7="received.html";
if (!(mail($theEmail7, stripslashes($theSubject7), stripslashes($theMessage7), stripslashes($theHeaders7)))) {
header ( "Location: $theErrorFile7" );
}else{
header ( "Location: $theThanxFile7" );
}
?>
The effective form of form validation on user side is to use jQuery validation plugin, see examples on proper usage.
Note: user ALWAYS can disable javascript or use some kind of bot to send invalid not checked data, so you always have to write proper server side validation.
Frameworks often provides effective way of form validation, such as Zend_Validator.
It's common to prepare method for your php application such as:
public function validate() {
if( !isset( $_POST['name'])){
$this->field = 'name';
$this->msg = 'Invalid user name';
return false;
}
...
return true;
}
And use it in both sending script:
if( $form->validate()){
send();
}
And in check script:
$data = array();
if( $form->validate()){
$data['status'] = 'ok';
} else {
$data['status'] = 'failure';
$data['field'] = $form->field;
$data['msg'] = $form->msg;
}
echo json_encode( $data);
End than use jquery and javascript for form validation "on the fly":
<input type="text" name="name" value="" onchange="ajaxValidate();" />
function ajaxValidate(){
// Call ajax to check script and put results
}
If you're just building small project with one form or so, you could implement few methods like:
function is_post( $key); // Shorter than write isset( $_POST[ $key])
function get_post( $key, $defaultValue); // Shorter than isset( $_POST[ $key]) ? $_POST[ $key] : $default
function is_email(...);
...
And jQuery validation:
function validateForm() {
$('.input').removeClass( 'error');
var status = true;
if( $('input[name=name]').val() == '')){
$('input[name=name]').addClass( 'error');
setMessage( 'Name cannot be empty');
status = false;
}
...
return status;
}
<form onsubmit='return validateForm();' ...>
You could try using the HTML5 required attribute... however this will only work with browsers that support it. For example:
<label for="name">Name:</label>
<input type="text" name="name" required="required" id="name">
This will only work if you use the HTML5 doctype though.
Then for the PHP validation in the instance the HTML5 validation hasn't run due to incompatible browser... or if JavaScript doesn't run due to it being disabled/unavailable/broken.
// check input
if (empty($_POST['name']))
{
$errors['name'] = 'Please provide your name.';
}
I then display the errors when I show the page to the user after the authentication has gone through.
<label for="name">Name:</label>
<input type="text" name="name" required="required" id="name">
<?php if (!empty($errors['name'])): ?><p class="error"><?php echo $errors['name']; ?></p><?php endif; ?>
Also... remember to protect yourself from SQL injection, XSS and mallicious code injection if this is going to be saved in a database or displayed to other users.
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:
if(isset($_POST['submit'])) {
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
$error = "";
} else {
$error = "Please fill in the required fields.";
}
}
In the form, I have a span class like so:
<span class="error">'.$error.'</span>
I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?
Thanks so much for any help or tips!
In order to process the form while staying on the page, you will need to incorporate some AJAX. The easiest way to do this is to use a framework of some sort (recommend jQuery). This should give you some insight into how to develop such functionality. If you get stuck, we're here to help.
http://api.jquery.com/jQuery.post/
Following your current model, I am assuming you do not mean AJAX and that you merely mean the server side code and form cohabitate on the same script. You can set the action of the form to $_SERVER['PHP_SELF'] first to ensure the proper action attribute is set.
Are you echoing out the error message within the span, or is all that output being placed after an echo statement?
echo '<span class="error">'.$error.'</span>'
Or, if not in the PHP context outside of script
<span class="error"><? echo $error; ?></span>
Also, you may want to consider using a mature php mailing solution like PHP Mailer to help set headers and ensure more effective delivery.
You don't need any AJAX.
$error = '';
if (isset($_POST['submit'])) {
if ( <<< insert check for required fields >>> ) {
// handle form, send mail, etc
// you may want to redirect on success to prevent double posting
} else {
$error = "Please fill in the required fields.";
}
}
Well without the rest of the page I'm not sure why this isn't working already but you should post back to the same page not just an empty action. I would do it this way.
<?php
$error = $name = $email = $phone = $comment = "";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
} else {
$error = "Please fill in the required fields.";
}
}else{ ?>
<div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="emailMonthlySpecials.php">
<span class="error><?php echo $error; ?></span>
Name: <input name="name" type="text" value="<?php echo $name;?>"/><br />
Email: <input name="email" type="text" value="<?php echo $email;?>"/><br />
Phone Number: <input name="phone" type="text" <?php echo $phone;?>"/><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"><?php echo $comment;?></textarea><br /><br />
<input type="submit" value="Submit Email"/>
</form></div>
<?php } ?>
When I handle form validations, I tend to create an array to hold the error messages, like so:
<?php
$error = array();
if( $POST ){
# Form is Submitted
if( /* TRUE if "email" is empty */ ){
$error['email'] = 'Please provide an Email Address';
}elseif( /* TRUE if "email" is not a valid address */ ){
$error['email'] = 'Please provide a Valid Email Address';
}elseif( /* TRUE if "email" is already associated with a User */ ){
$error['email'] = 'The Provided Email Address is Already Taken';
}
...
if( count( $error )==0 ){
# No Error has been Recorded
# Do Successful Things
}
} /* Closing if( $_POST ){ */
Then within the presentation/display section, I have something like:
<?php if( count( $error )>0 ){ ?>
<div id="error">
The following Errors have occurred:
<ul>
<?php foreach( $error as $k => $v ){ ?>
<li><?php echo $k; ?>: <?php echo $v; ?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
And within the form, something like:
<input name="email"<?php echo ( $error['email'] ? ' class="error"' : '' ); ?> />
This means that:
Customised, multi-tiered error messages can be recorded.
A summary of the error messages can be shown.
Fields associated with the error messages can be marked.
Has worked well in my experience thusfar.
Yep, I think You have two methods to do that, as already explained above...
When the form is submitted to the same page (itself) using *$_SERVER['PHP_SELF']*, you can check weather each posted field is empty using empty() function. Then if they are not filled then set the variable $error and then use echo $error; at the span of error... If no any error you can assign the default message at the $error instead of the error... It should do what you need...
You can use AJAX and send a request to the page and set the error message. Then the page is not fully refreshed as it was before, but only the element you wanted to refresh. This is fast, but in most of the cases, first method is preferred, unless AJAX is a need..
What exactly you want to do? If you specify what's your actual need, it is possible to provide some sample code... (First method is already discussed)
Thank You.
ADynaMic
My suggest is to use ajax call when submit,
according to the answer come back, you update the span of error.
you can find a lot of examples in web like
http://jqueryfordesigners.com/using-ajax-to-validate-forms/
http://www.the-art-of-web.com/javascript/ajax-validate/