I have a system where the user sends an email using a form (simple).
HTML form
<form method="post" action="process.php">
<label class="fieldLabel">Your email:</label><label class="errorLabel"><?php echo $form->error("email"); ?></label>
<input type="text" name="email" maxlength="100" class="email" value="<?php echo $form->value("email"); ?>" />
<label class="fieldLabel">Your enquiry:</label><label class="errorLabel"><?php echo $form->error("body"); ?></label>
<textarea name="body" class="enquiry"><?php echo $form->value("body"); ?></textarea>
<input type="submit" name="enquiry" class="button" value="Send Message"/>
</form>
On the same page, I have this if statement
if(isset($_SESSION['enq'])){
if($_SESSION['enq']){
echo "<h2>Your message has successfully been sent to Alan Slough.</h2>";
}
else{
echo"<h2>Oops, something went wrong. Please try again.</h2>";
}
unset($_SESSION['enq']);
}
Now the process.php file the form directs to
class Process{
//class constructor
function Process(){
if(isset($_POST['enquiry'])){
$this->enquiry();
}
}
function enquiry(){
global $session, $form;
//Registration attempt
$retval = $session->enquiry($_POST['email'], $_POST['body']);
//Successful
if($retval == 0){
$_SESSION['enq'] = true;
header("Location: contact-us.php");
}
//Error found with form
else if($retval == 1){
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: contact-us.php");
}
//Failed
else if($retval == 2){
$_SESSION['enq'] = false;
header("Location: contact-us.php");
}
}
};
And now the session page where everything happens
//enquiry being made
function enquiry($email, $body){
global $form;
//check email entered
$field = "email";
if(!$email || strlen($email = trim($email)) == 0){
$form->setError($field, "* Not entered");
}
//check body(s) entered
$field = "body";
if(!$body || strlen($body = trim($body)) == 0){
$form->setError($field, "* Not entered");
}
//if errors exist, send them back to the user
if($form->num_errors > 0){
return 1; //errors with form
}
else if($form->num_errors == 0){
$this->customerEnquiry($email, $body);
return 0; //successful
}
else{
return 2; //failed
}
}
//send the enquiry to the account email
function customerEnquiry($email, $body){
$from = "From: ".$email." <".$email.">";
$to = "random#email.com";
$subject = "Website enquiry from ".$email."";
return mail($to,$subject,$body,$from);
}
Ok my problem is that the errors aren't coming back if I don't fill in the form. Also, the success text isn't being displayed if I don't?
Anyone see a problem with how this flows?
Hoping I have just missed something simple!
Thanks!
I noticed this bit of code.
if(isset($_SESSION['enq'])){ // <---This...
if($_SESSION['enq']){ // <---And This
echo "<h2>Your message has successfully been sent to Alan Slough.</h2>";
}
else{
echo"<h2>Oops, something went wrong. Please try again.</h2>";
}
unset($_SESSION['enq']);
}
If $_SESSION['enq'] is not set, then the IF statement inside that will never execute, meaning you will see neither the success nor failure message.
Also, are you starting the session anywhere on the page? If you never start a session, then $_SESSION['enq'] will never be set.
http://www.php.net/manual/en/function.session-start.php
This is a very strange way to go about this. For example you're displaying success/failure message before the e-mail has been sent.
Have you copy and pasted this?
The usual method to do this would be to have the logic in process.php only, this is where you'd do your validation (return message to user if failed) and ultimately send the e-mail.
In the long run I think you'd be better off modifying the flow as I'm currently having a hard time trying to follow it.
Related
I have a fairly straight-forward validation system on my registration page within my website. It all works fine, however, it seems unnecessarily messy; with always checking if a variable ($regOpen) is true, and then setting a variable ($errors) to true each time there is an error.
This is the very simplified script and relative HTML:
<?php
$regOpen = false;
$errors = false;
if(Input::is("register")){ // if a user has clicked register
$regOpen = true;
}
if($regOpen){ // checking if input is set first time
if(Input::empty("email")){
echo '<span>Your email address must not be left blank.</span>';
$errors = true; // setting to true for the first time
}
if($email->exists()){
echo '<span>A user with that email already exists.</span>';
$errors = true; // 2nd
}
if(!filter_var(Input::get("email"), FILTER_VALIDATE_EMAIL)){
echo '<span>That is not a valid email type.</span>';
$errors = true; // 3rd
}
}
?>
<input type="text" name="email">
<?php
if($regOpen){ // 2nd
if(Input::empty("password")){
echo '<span>Your password must not be left blank.</span>';
$errors = true; // 4th
}
if(strlen(Input::get("password")) < 4){
echo '<span>Your password must be a minimum of 4 characters.</span>';
$errors = true; // 5th
}
}
?>
<input type="password" name="password">
<?php
if($errors){ // if there are errors
echo '<span>Registration failed.</span>';
} else {
// register user
echo '<span>Registration successful.</span>;
}
?>
In reality, I actually have about several fields I need to check (each with their own list of errors to check), so as you can imagine; checking and setting all these variables seems a bit tedious and unnecessary.
What I want to know is, if there is a way to only have to set the $errors variable to true, once. Not only that, if there is a way to reduce the way I check if $regOpen is true (instead of checking each time I need to check for errors).
Thanks.
You could use $errors as an array for errors instead of being just an indicator. Then you could check if $errors array is not empty, then it contains errors.
Here's a clearer version of your code:
<?php
function print_errors($errors) {
foreach($errors as $error) {
echo '<span>' . $error . '</span>';
}
}
$regOpen = Input::is("register");
$errors = [];
if($regOpen){ // checking if input is set first time
if(Input::empty("email")){
$errors['email'][] = "Your email address must not be left blank.";
}
if($email->exists()){
$errors['email'][] = "A user with that email already exists.";
}
if(!filter_var(Input::get("email"), FILTER_VALIDATE_EMAIL)){
$errors['email'][] = "That is not a valid email type.";
}
if(Input::empty("password")){
$errors['password'][] = "Your password must not be left blank.";
}
if(strlen(Input::get("password")) < 4){
$errors['password'][] = "Your password must be a minimum of 4 characters.";
}
}
?>
<?php isset($errors['email']) ? print_errors($errors['email']) : null; ?>
<input type="text" name="email">
<?php isset($errors['password']) ? print_errors($errors['password']) : null; ?>
<input type="password" name="password">
<?php
if(count($errors) > 0){ // if there are errors
echo '<span>Registration failed.</span>';
} else {
// register user
echo '<span>Registration successful.</span>';
}
?>
You may now get the idea.
First of all, many of the checking are not necessary at PHP level, you can use the HTML 5 form validation for many cases. Secondly, for a few case that HTML5 form validation can't handle, you don't need to purposely set $errors=true, you could do something like $error=$email->exists();.
I am trying to validate my RSVP form using only PHP. The user should receive an error message when the form is incomplete. I am trying to avoid the use of jQuery.
I am using this tutorial:
http://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/
The form is functioning fine but I haven't been able to get the error messages to display at all. I am using Wordpress and I want the form to appear at the footer of every page; not sure if this complicates matters. Here is my code:
<?php
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='success'>{$message}</div>";
} else {
$response = "<div class='error'>{$message}</div>";
}
}
//response messages
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//variables defined for messages
$email = $_POST["rsvp_email"];
$name = $_POST["rsvp_name"];
$attend = $_POST["rsvp_attend"];
$number = $_POST["rsvp_number"];
//variables defined for message to admin
$to = get_option('admin_email'); //sending to wordpress admin email
$subject = "Just Kidding You Foo";
$headers = "From: $email\n";
$message = "$name $attend.\n RSVPs $number of people";
//conditional statements used for form validation
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
my_contact_form_generate_response("error", $email_invalid);
} else { //email is valid
//validate presence of name and message
if(empty($name) || empty($attend) || empty($number)) {
my_contact_form_generate_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to,$subject,$message,$headers);
if($sent) {
my_contact_form_generate_response("success", $message_sent); //message sent!
} else {
my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
?>
<div id="page-rsvp">
<h1>RSVP</h1>
<div id="respond">
<?php echo $response; ?>
<form action="<?php the_permalink(); ?>" method="post">
<!--Name here-->
<div class="rsvp-full"><label for="rsvp_name"><input type="text" name="rsvp_name" value="Your name"></label></div>
<div class="rsvp-full"><label for="rsvp_email"><input type="text" name="rsvp_email" value="Your email"></label></div>
<!--status of attendance-->
<div class="rsvp-full">
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="accepts">Accepts</div>
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="declines">Declines</div>
</div>
<!--number of guests attending-->
<div class="rsvp-full"><input type="number" name="rsvp_number" min="1" max="5">Total number of guests attending</div>
<div id="submit-button" class="rsvp-full"><input id="submit-button" type="submit"></div>
</form>
</div>
</div>
TIA!!!
I'm not that familiar with WP, but if I understand correctly, I believe you're trying to ensure all the fields are filled out.
Check your brackets! You need to be sure your curly brackets are opening and closing where you want them to. Otherwise the output of the page won't display. I write in all my braces because I'm not smart enough to be sure I know where they start and stop. I've taken the liberty of editing them into your question. I believe there was one missing at the end.
Once I fixed the brackets and removed functions my computer didn't have, it worked fine.
Tip 0: Try turning error reporting on for this script - error_reporting(E_ALL); at the top of this script. I always do for development.
Tip 1: use the placeholder attribute instead of value for things like "your name".
Tip 2: make sure the $_POST vars are set. I would do this by checking if they're set and then setting them to '' if they aren't; something like this:
//variables defined for messages
// you could do it like this:
if (isset($_POST["rsvp_email"])) {
$email = $_POST["rsvp_email"];
} else {
$email = '';
}
// or like this:
$name = '';
if (isset($_POST["rsvp_name"])) {
$name = $_POST["rsvp_name"];
}
// or even using a ternary operator:
$attend = isset($_POST["rsvp_attend"]) ? $_POST["rsvp_attend"] : '';
//but this will trigger a "Notice" error if the post var isn't set.
$number = $_POST["rsvp_number"];
I'm aware that this question has been asked a huge number of times but the answers seem really specific to the script posted and with my current knowledge I can't make the transition from the corrected script to implementing it into my own.
This all works fine - it submits on the same page and provides feedback of any errors, but I want any errors to be echoed beneath the form making it more convenient for the user to just change what they entered incorrectly and re-submit.
From what I can gather from the questions I read before posting this - it may only be possible using jQuery/Ajax?
My script:
<?php
if(isset($_POST['submit'])){
require "connection.php";
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$repeat_password = $_POST["repeat_password"];
$username_query = mysql_query("SELECT id FROM users WHERE username = '$username'");
$email_query = mysql_query("SELECT id FROM users WHERE email = '$email'");
if($username == "" || $password == "" || $repeat_password == "" || $email == ""){
die("All boxes must be filled out!");
}// ^ Checking if all boxes have been filled out
else {
if (!ctype_alnum($username)){
die("Username can only contain letters and numbers");
}// ^ Checking if username is alphanumeric
else {
if (strlen($username) < 6 || strlen($username) > 15){
die("Username must be between 6-15 characters.");
}// ^ Checking if username is between 6-15 characters
else {
if (mysql_num_rows($username_query) != 0){
die("Username is taken, please choose another.");
}// ^ Checking if username exists in database
else {
if (!preg_match("/[0-9]/",$password)){
echo "password doesnt contain a number";
}
else {
if ($password != $repeat_password){
die("Passwords do not match");
}// ^ Checking if password and repeat_password match
else {
if (strlen($password) < 6){
die("Password must be atleast 6 characters long.");
}// ^ Checking if password is longer than 6 characters
else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
die("E-mail address is not vaild.");
}// ^ Checking if e-mail address is valid
else {
if (mysql_num_rows($email_query) != 0){
die("This e-mail address has already been used to create a different account.");
}// ^ Checking if e-mail address has already been used
else {
mysql_query("INSERT INTO users (username, password, email, signup_date) VALUES ('$username', '$password', '$email', CURDATE())") or die(mysql_error());
echo "Account succesfully created, welcome ".$username."!";
}
}
}
}
}
}
}
}
}
exit;
}
//
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>
Username:
</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td>
Repeat password:
</td>
<td>
<input type="password" name="repeat_password">
</td>
</tr>
<tr>
<td>
E-mail:
</td>
<td>
<input type="email" name="email">
</td>
</tr>
<tr>
<td colspan="2">
<center><input type="submit" name="submit"></center>
</td>
</tr>
</table>
</form>
Answer: Yes, you have to use jQuery there.
You can validate form just after user entered 1st letter. You can validate on key up/down or on submit. I suggest to use jQuery Validation Plugin.
To sumbit form use ajax requests. It is rly simple. You can read about it here. There are some examples at the end page I had given.
Note, that if you will use jQuery Validation Plugin you can send ajax request on valid action. Using this, ajax request with serialized form will be sent on form submit + on form valid. If form has some invalid fields, errors will be shown, if there are no errors, ajax-request will be send.
Advice:
Your arhitecture not very good. Why? If people will write bad name and make 10 more other errors, only 1 error:
Username can only contain letters and numbers
will be shown. Why? Because of you arhitecture. After that he will correct 2nd erorr. 3rd error etc.
I suggest you do to handle errors this way:
$errors = array();
$errorsFlag = false;
if(check_username1()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
if(check_username2()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
if(check_mail()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
And how to output it? Use this:
if($errorsFlag == true) {
foreach($errors as $error) {
echo $error . " <br /> ";;
}
}
yes, you'll need javascript. but not necessarily jQuery or ajax.
but php without the use of ajax always needs you to reload the page cause otherwise the php-code will not be executed.
search for some kind of javascript/jQuery validation scripts if you don't want the page to be reloaded. otherwise (if you don't care about page-reloading), you can put out your error message at the end of the form with php as well.
I always set my errors as a session. This allows you to set multiple errors at once, and print them wherever you want.
The following if statements are just examples of where you would set the errors...
session_start(); //you will need this
if ( username_exists($un) ) {
handleError("Username already exists!");
}
...
if ( !passwordIsStrong($pw) ) {
handleError("Password is not strong enough!");
}
Here's the functions that actually set/print the errors.
function handleError( $err ) {
//get any existing errors
$existing = isset($_SESSION['form-errors']) ? $_SESSION['form-errors'] : '';
//append the new error to the existing ones. Over-write the session with new data.
$_SESSION['form-errors'] = "$existing<li>$err</li>";
}
function getErrors() {
if( isset($_SESSION['form-errors']) )
echo $_SESSION['form-errors'];
}
getErrors(); can be called anywhere in your html. It will print something like this...
<li>Username already exists!</li>
<li>Password is not strong enough!</li>
It's kind of like a log. But it's worked for me on all of my projects!
I have a problem with my PHP script, which checks 3 variables (code below):
$auth (The mail author)
$subj (The mail subject)
$text (The mail message)
FORM:
(NOTE: I used the "GET" method because for some strange reason the "POST" method didn't work)
<div id="contact_form">
<form method="get" name="contact" action="home.php">
<input type="hidden"
name="method"
value="send"/>
E-Mail:<br/>
<input type="text"
id="author"
name="author"
class="require input_field"
value=""/>
<br/>
Subject:<br/>
<input type="text"
id="subject"
name="subject"
class="require input_field"
value=""/>
<br/>
Message:<br/>
<textarea id="text"
name="text"
rows="0"
cols="0"
class="required"
value=""></textarea>
<br/>
<input type="submit"
class="submit_btn"
name="submit"
id="submit"
value="Submit" />
</form>
</div>
The form works just fine now.
PHP:
<?php // ||HOME.PHP||
$method = $_GET['method'];
$auth = $_GET['author'];
$subj = $_GET['subject'];
$text = $_GET['text'];
$recv = "mymail#stuff.com";
function redirect($location) {
if($location == "true") {
header("Location: http://mysite.com/home.php?method=result&status=true");
} else {
header("Location: http://mysite.com/home.php?method=result&status=false");
}
}
//...
//Other methods...
//...
//METHOD SEND
if($method == "send") {
//HERE IS THE PROBLEM
//These are apparently not working
//If i leave the form blank and submit it
//these won't redirect to "false" (mail not sent),
//and the script will just continue, send the empty mail
//and redirect to "true" (mail sent)
if(empty($auth)) { redirect(""); }
if(empty($subj)) { redirect(""); }
if(empty($text)) { redirect(""); }
if(!strstr($auth, '#')) { redirect(""); }
if(!strstr($auth, '.')) { redirect(""); }
if(strlen($auth) < 5) { redirect(""); }
if(strlen($subj) < 4) { redirect(""); }
if(strlen($text) < 4) { redirect(""); }
//From here it should work just fine
//As i'm not sure the "RESULT" method (below) is working fine, i
//posted it too.
$auth = "From: " . $auth;
mail($recv,$subj,$text,$auth);
redirect("true");
require("template/footer.html");
exit(0);
}
//METHOD RESULT
if($method == "result") {
$status = $_GET['status'];
if($status == "true") {
echo "mail sent";
} else {
echo "mail not sent";
}
?>
<script language="javascript">
setTimeout("location.href = 'http://adteam.altervista.org/home.php';", 5000);
</script>
<?php
exit(0);
} ?>
The problem is explained in the PHP code (in the comments below the "SEND" method).
Do you guys have any suggestion?
You need to stop the script execution after you've set the redirect headers. Otherwise it will just continue to sending the mail and set new redirect headers before any headers are sent to the browser.
function redirect($location) {
if($location) {
header("Location: http://mysite.com/home.php?method=result&status=true");
} else {
header("Location: http://mysite.com/home.php?method=result&status=false");
}
die();
}
Note that if( $location == "true" ) is kind of an anti-pattern; it's better to use boolean true and false instead of strings.
Should be easy. Your saying that "" is false. But it ain't: because "" is true, but empty which is true. false is not set or specified false. So you should do:
function redirect($location) {
if($location) {
header("Location: http://mysite.com/home.php?method=result&status=true");
exit();
} else {
header("Location: http://mysite.com/home.php?method=result&status=false");
exit();
}
}
And use: redirect(true) / redirect(false);
A string will always evaluate to true, even if it is empty. That's precisely the reason why we check strings using empty() as opposed to isset(). A few more things:
You should be using POST to submit the email.
You should probably check if the form was actually submitted before validating the input.
You should create and display specific error messages telling the user what required fields they did not complete.
You should run some careful validation routines on the input to avoid having your email form used to send spam and malware.
Simply add exit in false branch:
function redirect($location) {
if($location == "true") {
header("Location: http://mysite.com/home.php?method=result&status=true");
} else {
header("Location: http://mysite.com/home.php?method=result&status=false");
exit(0); //simply add it here
}
}
header function does not stop further execution by itself and you must stop doing anything else if do not want to send an email when something is wrong.
Actually, you may simply add exit after if statement.
I am wondering if anyone out there can help with my form Validation Please?
I am having a few problems trying to synchronized out how certain bits of the actual structure of the script works together.
<?php
$flag="OK"; // This is the flag and we set it to OK
$msg=""; // Initializing the message to hold the error messages
if(isset($_POST['Send'])){
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=num_key){
$msg=$msg."Your Key not valid! Please try again!<BR>";
$flag="NOTOK";
}
else{
$msg=$msg."Your Key is valid!<BR>";
$flag="OK";
}
}
$email=$_POST['email'];
echo "Your Email: ".$email." is";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$msg=$msg."Invalid email<BR>";
$flag="NOTOK";
}else{
$msg=$msg."Valid Email<BR>";
$flag="OK";
}
$password=$_POST['password'];
if(strlen($password) < 5 ){
$msg=$msg."( Please enter password of more than 5 character length )<BR>";
$flag="NOTOK";
}
if($flag <>"OK"){
echo "$msg <br> <input type='button' value='Retry' onClick='history.go(-1)'>";
}else{ // all entries are correct and let us proceed with the database checking etc …
}
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['email']))
{//if "email" is filled out, proceed
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
}
?>
the problem, when email valid, password valid, though key is invalid the warning of key disappear, it mean passed too... and also the spamcheck doesn't look work..
You don't have to set the flag to 'OK' or a previous error get masked, as you already noted.
If all the check are ok, the flag remains in valid state and you can pass on, otherwise, if one of the check fails the flag reports the incorrect state.
$flag="OK"; // This is the flag and we set it to OK
$msg=""; // Initializing the message to hold the error messages
if(isset($_POST['Send'])) {
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=$num_key){
$msg=$msg."Your Key not valid! Please try again!<BR>";
$flag="NOTOK";
} else {
$msg=$msg."Your Key is valid!<BR>";
}
}
$email=$_POST['email'];
echo "Your Email: ".$email." is";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$msg=$msg."Invalid email<BR>";
$flag="NOTOK";
}else{
$msg=$msg."Valid Email<BR>";
}
$password=$_POST['password'];
if(strlen($password) < 5 ){
$msg=$msg."( Please enter password of more than 5 character length )<BR>";
$flag="NOTOK";
}
if($flag <>"OK"){
echo "$msg <br> <input type='button' value='Retry' onClick='history.go(-1)'>";
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Said that I would use a different approach, for example using boolean values other than a string named flag. You can obtain a more fluent code calling it something like $inputIsvalid.
Other nags: Sometimes you add the messages to a $msg variable, other you issue an echo, maybe it is an oversight.
There is a lot of room for improvements, as every other code, I will address just some of the easy issues, for examples I will not check if the variables are set or not.
$inputIsValid=true; // This is the flag and we set it to OK
$messages = array(); // Initializing the message to hold the error messages
if(isset($_POST['Send'])) {
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=$num_key){
$messages[]= 'Your Key not valid! Please try again!';
$inputIsValid=false;
} else {
$messages[]'Your Key is valid!';
}
}
$email=$_POST['email'];
$emailRegex='^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$';
$emailIsValid = eregi($emailRegEx, $email);
$messages[]= 'Your Email: '.$email.' is ' .($emailIsValid? 'Valid':'Invalid');
$inputIsValid = $inputIsValid && emailIsValid;
$password=$_POST['password'];
if(strlen($password) < 5 ){
$messages[]='( Please enter password of more than 5 character length )';
$inputIsValid=false;
}
if(!inputIsValid){
$messages[]='<input type='button' value='Retry' onClick='history.go(-1)'>';
echo join('<br/>', $messages);
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Another approach should be (the functions are quite simple, but you can modify the validation policy of the different components without affecting the main code):
function validateKey() {
if(!isset($_POST['Send'])) {
return true;
}
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
return $key==$num_key;
}
function validateEmail($email) {
$emailRegex='^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$';
return eregi($emailRegEx, $email);
}
function validatePassword($password) {
return strlen($password) < 5;
}
$inputIsValid=true; // This is the flag and we set it to OK
$messages = array(); // Initializing the message to hold the error messages
if(validateKey()) {
$messages[]'Your Key is valid!';
} else {
$messages[]= 'Your Key not valid! Please try again!';
$inputIsValid=false;
}
$emailIsValid = validateEmail($_POST['email']);
$messages[]= 'Your Email: '.$email.' is ' .($emailIsValid? 'Valid':'Invalid');
$inputIsValid = $inputIsValid && emailIsValid;
$password=;
if(!validatePassword($_POST['password']){
$messages[]='( Please enter password of more than 5 character length )';
$inputIsValid=false;
}
if(!inputIsValid){
$messages[]='<input type='button' value='Retry' onClick='history.go(-1)'>';
echo join('<br/>', $messages);
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Spam function:
why are you using Constant different than the boolena values?
(TRUE is different from true and FALSE is different from false)
You can rewrite the function like this in order to obtain the desired behaviour.
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
return filter_var($field, FILTER_VALIDATE_EMAIL);
}
if (isset($_POST['email'])) {//if "email" is filled out, proceed
$mailcheck = spamcheck($_POST['email']);
if (!$mailcheck) {
echo "Invalid input";
}
}
Each of you tests sets flag to "OK" or "NOTOK" overwriting decisions made by previous tests.
You could start with $flag = true;. And only if a test decides that the input is unsatisfying it sets $flag=false.
Or you can remove $flag altogether and check if 0===strlen($msg) after the tests.