Jump to content

PHP Validation Problem.


phprookie125

Recommended Posts

Hello everyone.

 

First of all let me introduce myself. I'm a Graduate web designer with emphasis on Design but I do like to dabble in code here and there.  I love to design interfaces and mess around a little bit with Actionscript and i have a little experience with php.

 

What I've got here is a php script (global license so I can use it) that I've attached to my web server.  I've managed to tailor it so it validates all the fields I want, however the form still goes to my email whether or not there are validation errors. That is, even if the php picks up a validation error the data is still sent to the server.

 

Can anyone please advise as to the script I need to solve this please? Obviously I don't want to burden someones email account with duff data when the site goes live  :-)

 

Thanks

 

phprookie125

 

 

<?php

include "formvalidator.php";

$show_form=true;
?>

<?php
/***************************************/
//Start to build the email details
$my_email = "myemailaddress@here.com";
$continue = "index.html";

/**/
$errors = array();

// Remove $_COOKIE elements from $_REQUEST.

if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}

// Check all fields for an email header.

function recursive_array_check_header($element_value)
{

global $set;

if(!is_array($element_value)){if(preg_match("/(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)/i",$element_value)){$set = 1;}}
else
{

foreach($element_value as $value){if($set){break;} recursive_array_check_header($value);}

}

}

recursive_array_check_header($_REQUEST);

if($set){$errors[] = "You cannot send an email header";}

unset($set); 

// Validate email field.

/**/if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{

if(preg_match("/(%0A|%0D|\n+|\r+|:)/i",$_REQUEST['email'])){$errors[] = "Email address may not contain a new line or a colon";}

$_REQUEST['email'] = trim($_REQUEST['email']);

if(substr_count($_REQUEST['email'],"@") != 1 || stristr($_REQUEST['email']," ")){$errors[] = "Email required.";}else{$exploded_email = explode("@",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "You must include your email!";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid - editor note not validator.php";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}

}

// Check referrer is from same site.

if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}

// Check for a blank form.

function recursive_array_check_blank($element_value)
{

global $set;

if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{

foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}

}

}
/**/
recursive_array_check_blank($_REQUEST);

if(!$set){$errors[] = "You cannot send a blank form";}

unset($set);

// Display any errors and exit if errors exist.

if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}

if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}

// Build message.

function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}




if(true == $show_form)
{

$message = build_message($_REQUEST);

$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."";

$message = stripslashes($message);

$subject = "Enquiry from Website";

$headers = "From: Website " . $_REQUEST['email'];

mail($my_email,$subject,$message,$headers);
?>

<!--html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Auto Cleanse North East - Mobile Valeting and Detailing</title>
    
        <link rel = "stylesheet" type = "text/css" href = "../styles/mobile.css" />
        <link rel = "stylesheet" type = "text/css" href = "../styles/formatting.css" />
        <link rel = "stylesheet" type = "text/css" href = "../styles/style.css" />
        <link rel = "stylesheet" type = "text/css" href = "../styles/nav.css" />
        <link rel = "stylesheet" type = "text/css" href = "../styles/forms.css" />
</head>

<body>


<div id = "container">


<div id = "logoBanner">
	<a href = "../autoCtmp.html"><img src="../images/top.png" alt="Auto Cleanse North East Logo - North East Best Mobile Valeting and Detailing" border="0" usemap="#Map" /></a>
        
        <map name="Map" id="Map">
          <area shape="rect" coords="749,85,777,113" href="http://uk.linkedin.com/pub/sam-payne/20/a01/131" target="_new" alt="View Auto Cleanse LinkedIn Profile" />
          <area shape="rect" coords="747,53,779,82" href="https://twitter.com/#!/AutoCleanseNE" target="_new" alt="Auto Cleanse North East is on Twitter!" />
          <area shape="rect" coords="748,18,776,48" href="http://www.facebook.com/pages/Auto-Cleanse-North-East/232831036748006" target="_new" alt="View our Facebook Page!" />
        </map>

</div>
    
    <div id = "navigationBanner">
    	<img src="../images/navi.png" />
    </div>
    
   <div id = "navText"><a class = "navLink" href = "autoCtmp.html">home</a></div> <!---->
    
    
    <div id = "navTextAbout"><a class = "navLinkAbout" href = "../about.html">ABOUT</a></div>   
<div id = "navTextPrices"><a class = "navLinkPrices" href = "../prices.html">PRICES & SERVICES</a></div>
  <div id = "navTextCarpets"><a class = "navLinkCarpets" href = "../carpets.html">CARPETS & UPHOLSTERY</a></div>
    <div id = "navTextGallery"><a class = "navLinkGallery" href = "../gallery.html">GALLERY</a></div>
<div id = "navTextContact"><div id = "selected">CONTACT</div></div><!---->

<div id = "topLinks"><a class ="topLinkStyle" href = "xxx.html">Mobile</a> | <a class = "topLinkStyle" href = "xxx.html">Low Graphics</a>
</div>

    <div id = "mainBannerSub">   

      <div id = "textFormatSub">
        <div id = "textFormatTitle">Contact Us!</div>
        
<br /><?php if(isset($_POST['sendQuery']))
{
    $validator = new FormValidator();
    $validator->addValidation("name","req","Please fill in Name");
$validator->addValidation("lastName", "req", "Please fill in lastName");
    $validator->addValidation("contact_Email","email", "**Not a valid email please try again***");
    $validator->addValidation("contact_Email","req","Please give an Email");
    if($validator->ValidateForm())
    {
        echo "<b>Thank you for contacting us! We have received your message and will contact you shortly<br /</b>";
        $show_form=true;
    }
    else if (!isset($_POST['Submit']))
    {
        echo "<B>Validation Errors:</B> - Please see below and correct";
        $error_hash = $validator->GetErrors();
        foreach($error_hash as $inpname => $inp_err)
        {
          echo "<p>$inpname : $inp_err</p>\n";
	  $show_form=false;
        }
	echo "<a class = 'emailLink' href = '../contact.html'>Click here to return to the contact page</a>";		
    }
} ?>

Link to comment
Share on other sites

I'm not going to read through all of that and try and decipher, but it looks like you are using an array to compile the errors. So, the solution should be pretty simple. For whatever code you do not want to process when there are errors (i.e. the code to send an email) wrap it in an if() conditional based upon whether that array has any elements.

 

if(!count($errors))
{
    //Send the email only if there are no elements in $errors array
}

Link to comment
Share on other sites

I think the main problem is the error variable refers to another set of validations that the code doesn't seem to pick up. But I really want to stick with this if I can because it's the closest i've ever come to validation.

 

So near but yet so far! But unfortunately no matter what i;ve tried the condition you offered has had no effect.  :)

Link to comment
Share on other sites

I'm not following you. If you don't know what your variables are doing you need to figure that out first. I routinely use an $errors array and do exactly as I described above. Do you define $errors as an empty array at the beginning of your code? If not, then that logic won't work.

 

In other words, what do you get when using that condition? Do you get an error or does $errors have a count at that point? Did you test it (i.e. echo the count() of $errors)?

Link to comment
Share on other sites

As i said before I'm not practised in php although I do have a little experience, I did a little bit for my degree. So you'll probably find me a little frustrating.    :shy:

 

The script doesn't count anything but it displays each and every error it finds and guides the user what to do to fix it, what I tried to say was the error variable isn't compatible with the actual validations the code.  In other words I think I've overcomplicated things for myself.

 

I guess i'll have to try something different

Link to comment
Share on other sites

Here is a basic idea of the process I use. Maybe it will help:

 

//Create array to store validation errors
$errors = array();

//Perform validations
if(empty($name)) { $errors[] = "Name is required"; }
if(empty($email)) { $errors[] = "Email is required"; }
if(empty($password)) { $errors[] = "Password is required"; }
elseif(strlen($password)<8 || strlen($password)>16) { $errors[] = "Password must be between 8 and 16 characters"; }
elseif($password != $passwordMatch) { $errors[] = "Passwords do not match"; }

//Check if there were errors
if(!count($errors))
{
    //There were no errors, process the results (i.e. insert/update db records)
}
else
{
    //There were errors, show them
    echo "The following errors occurred:<br>\n";
    foreach($errors as $err)
    {
        echo " - {$err}<br>\n";
    }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.