Jump to content

PHP Email Form - How to make errors stop the email from sending


echs

Recommended Posts

Hi good people of w3, I'd been using the tutorials on this site a lot in an attempt to get the email enquiry form working for the website I've been putting together for the place I'm currently employed at. This isn't exactly my forte, I'm pretty decent when it comes to html but php is an animal I'm only just starting to become familiar with.I have an issue currently where particular parts of the form are required to be filled in, and I can successfully generate errors when this does not occur. However, the errors do not actually stop the email from being sent and hence we end up with incomplete enquiries on the other side when the form is not correctly filled in.If anyone could provide some advice as to a means to make the errors stop the email from being sent, that would be much appreciated. The relevant code is below.

<?php// define variables and set to empty values$nameErr = $emailErr = $partErr = $phoneErr = "";$name = $email = $part = $comments = $model = $brand = $phone = $contact_method = $product = $breakdown = "";if ($_SERVER["REQUEST_METHOD"] == "POST") {	  if (empty($_POST["name"])) {    $nameErr = "Name is required";  } else {  $name = test_input($_POST["name"]);      // check if name only contains letters and whitespace    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {      $nameErr = "Only letters and white space allowed";     }  }      if (empty($_POST["email"])) {    $emailErr = "Email is required";  } else {  $email = test_input($_POST["email"]);      // check if e-mail address is well-formed    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {      $emailErr = "Invalid email format";     }  }  	if (empty($_POST["phone"])) {    $contact_methodErr = "Phone number is required";  } else {    $phone = test_input($_POST["phone"]);  }    $contact_method = test_input($_POST["contact_method"]);  $brand = test_input($_POST["brand"]);  $product = test_input($_POST["product"]);  $model = test_input($_POST["model"]);  $breakdown = test_input($_POST["breakdown"]);      if (empty($_POST["part"])) {    $partErr = "Part number or description is required";  } else {  $part = test_input($_POST["part"]);  }    $comments = test_input($_POST["comments"]);  }    function test_input($data) {  $data = trim($data);  $data = stripslashes($data);  $data = htmlspecialchars($data);  return $data;}// Function to validate against any email injection attemptsfunction IsInjected($str){  $injections = array('(n+)',              '(r+)',              '(t+)',              '(%0A+)',              '(%0D+)',              '(%08+)',              '(%09+)'              );  $inject = join('|', $injections);  $inject = "/$inject/i";  if(preg_match($inject,$str))    {    return true;  }  else    {    return false;  }} //Validate firstif(IsInjected($customer_email)){    echo "Bad email value!";    exit;}			$email_from = 'sales@speedyspares.com';//<== update the email address		$email_subject = "Online Enquiry";		$email_body = '<html><body>';		$email_body .= '<table rules="all" style="border-color: #666;" cellpadding="10">';		$email_body .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . $name = $_POST["name"] . "</td></tr>";		$email_body .= "<tr><td><strong>Email:</strong> </td><td>" . $email = $_POST["email"] . "</td></tr>";		$email_body .= "<tr><td><strong>Phone:</strong> </td><td>" . $phone = $_POST["phone"] . "</td></tr>";		$email_body .= "<tr><td><strong>Preferred Method of Contact:</strong> </td><td>" . $contact_method = $_POST[	"contact_method"] . "</td></tr>";		$email_body .= "<tr><td><strong>Brand:</strong> </td><td>" . $brand = $_POST["brand"] . "</td></tr>";		$email_body .= "<tr><td><strong>Product:</strong> </td><td>" . $product = $_POST["product"] . "</td></tr>";		$email_body .= "<tr><td><strong>Model:</strong> </td><td>" . $model = $_POST["model"] . "</td></tr>";		$email_body .= "<tr><td><strong>Breakdown Required:</strong> </td><td>" . $breakdown = $_POST["breakdown"] . "</td></tr>";		$email_body .= "<tr><td><strong>Part:</strong> </td><td>" . $part = $_POST["part"] . "</td></tr>";		$email_body .= "<tr><td><strong>Comments:</strong> </td><td>" . $comments = $_POST["comments"] . "</td></tr>";		$email_body .= "</table>";		$email_body .= "</body></html>";    		$to = "sales@speedyspares.com";//<== update the email address		$headers = "From: $email_from rn";		$headers .= "Reply-To: $email rn";		$headers .= "MIME-Version: 1.0rn";		$headers .= "Content-Type: text/htmlrn";		//Send the email!		mail($to,$email_subject,$email_body,$headers);		//done. redirect to thank-you page.		header('Location: thankyou.html');  ?><form method="post" name="enquiry-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">        <h6><strong><span class="redasterisk">*</span></strong>denotes a required field</h6>        <h6>Name:<span class="error">* <?php echo $nameErr;?></span><br>          <input name="name" type="text" size="50">          <br>          E-mail:<span class="error">* <?php echo $emailErr;?></span><br>          <input name="email" type="text" size="50">          <br>          Phone:<span class="error">* <?php echo $phoneErr;?></span><br>          <input name="phone" type="text" size="50">          <br />          Preferred Contact Method:<br />          <input type="radio" name="contact" value="email" />          Email          <input type="radio" name="contact" value="phone" />          Phone          <br />          Brand:<br>          <select name="brand">            <option value="Sony">SONY</option>            <option value="Sharp">SHARP</option>            <option value="Hills">HILLS</option>            <option value="Other">OTHER</option>            </select><br />          Product:<br>          <select name="product">            <option value="TV">TV/PROJECTOR</option>            <option value="VIDEO">HOME VIDEO/DVD/BLU-RAY</option>            <option value="AUDIO">HOME AUDIO/THEATRE SYSTEM</option>            <option value="CAMERA">DIGITAL STILL CAMERA</option>            <option value="CAMCORDER">VIDEO CAMERA/CAMCORDER</option>            <option value="VAIO">PERSONAL COMPUTER (VAIO)</option>            <option value="EREADER">eBOOK READER</option>            <option value="PAUDIO">PERSONAL AUDIO</option>            <option value="CAUDIO">CAR AUDIO</option>            <option value="FRIDGE">REFRIDGERATOR</option>            <option value="MICROWAVE">MICROWAVE</option>            <option value="OTHER">OTHER</option>            </select><br />          Model :<br /><em>(eg. KDL-46HX800)</em><br>          <input type="text" name="model" size="50">          <br />          <input type="checkbox" name="breakdown" value="Yes" />          Request Breakdown<br />          Part number/description:<span class="error">* <?php echo $partErr;?></span><br /><em>(e.g. UWA-BR100 Wi-fi Adaptor)</em><br />          <input type="text" name="part" size="50">          <br>          Comments:<br>          <textarea name="comments" cols="50" rows="5">Please supply any additional information that may assist with your enquiry. (color/size/location etc.)</textarea>          <br />          (Please do not use this form for submission of credit card information)</h6>          <h5>             <input type="submit" name="submit" value="Submit">            <input type="reset" name="reset" value="Reset">          </h5>        </form>
Link to comment
Share on other sites

Wrap all of the code that actually sends the email in an if statement where you check your error variables to make sure they don't have any error messages. Or, you can add another variable called $isError or something, set it to false initially, and if any error happens then set it to true. Then you can check that one variable instead of all of the error message variables.

Link to comment
Share on other sites

Thanks for the advice. Unfortunately I am very much a novice when it comes to this and understand much better with examples. Would anyone be able to provide an quick example of the if/else code that would work for this situation? I don't need the full thing, just the lines involving what to wrap the email code in. Apologies for making what must be very noob requests.

Link to comment
Share on other sites

$isError = false;if ($_SERVER["REQUEST_METHOD"] == "POST") {if (empty($_POST["name"])) {$isError = true;$nameErr = "Name is required";}...if (empty($_POST["phone"])) {$isError = true;$contact_methodErr = "Phone number is required";}...if(IsInjected($customer_email)){$isError = true;echo "Bad email value!";}if(!$isError){$email_from = 'sales@speedyspares.com';//<== update the email address$email_subject = "Online Enquiry";...}
Edited by JamesB
  • Like 1
Link to comment
Share on other sites

Hmm... that seems to send emails either way, also sending them as soon as the page is accessed...maybe the last bit of code to send the email needs to be if(!$isError = false) or something like that?

Edited by echs
Link to comment
Share on other sites

Hello, I thought I'd suggest an alternative solution for you. This is based on the assumption that you are start with a form on a page written in HTML with the action set to "your/phpPage.php". You might try checking for filled in fields before the form is submitted.

 

I am also assuming this is done with a button with no type attribute of an input of type "submit". In your HTML, for your push button use this: <button type="button" onclick="example">Send</button> The type makes the button not submit when clicked. Instead, you will check contents of the form before submitting it. You will do this with the following javascript written within your HTML page:

function example(){	if( document.formNme.name == ""||		document.formNme.email == ""||		document.formNme.msg == "")	{		alert("Please fill in the missing information.");		if(document.formNme.name == ""){document.formName.name.focus();}		if(document.formNme.email == ""){document.formName.email.focus();}		if(document.formNme.msg == ""){document.formName.msg.focus();}	}else{	document.formNme.submit();	}}

The if part of this functions checks for empty fields in the form. If true (an empty field is found), it tells the user something is missing then gives focus to the firse empty. If false (the form is all filled in), it submits the form to whatever the form's action attribute wants. This way your PHP page never sees any empty field in the first place.

 

I hope this helps. :Pleased:

Edited by ceh2624
Link to comment
Share on other sites

try changing:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

to

if ($_SERVER["REQUEST_METHOD"] != "POST") {$isError = true;}else {

that should stop sending the email when the page is accessed.

 

Huzzah! That seems to have done the trick. Now I only seem to have one final issue. The email sends if there are no errors, but the form doesn't redirect to the thankyou.html page when submitted anymore. Any ideas?

Link to comment
Share on other sites

You should be able to put the location header after the email sends, then you'll want to stop PHP from outputting anything because it wouldn't matter anyway. But keep in mind that a header redirect will not work if you've sent any output to the browser before you send the header, you need to send the header before sending any other output. There's no reason to send any output at all if you're going to redirect though.

Link to comment
Share on other sites

Actually, after re-reading that about 20 times I think I finally got my head around it. So what you're saying is (I think), that because the form is outputting something before the header, that's why it's not showing the thankyou page when it's submitted. I think.So... I guess I need to either move the header redirect before the output code... or use something else to redirect to the thankyou page after submission?

Link to comment
Share on other sites

The way HTTP works is that each request from the browser to the server, and then the response from the server back to the browser, consists of a few parts (usually, some requests only have 1). When you submit a form, for example, the request that goes from the browser to the server has 2 parts. The first is all of the HTTP headers. The headers tell the server things like which file you are requesting, the type of request (get, post, etc), information about the browser itself, all kinds of stuff. For a post request, after the headers comes the request body, which contains all of the data submitted in the form. When the server responds it does the same thing, it sends all of the response headers first (things like asking the browser to set a cookie, or redirect, or all kinds of other things), and then the response body, which is usually the contents of the URL that the browser requested (i.e., an HTML page). So the headers always come first, then the body.So, when you're using PHP, and assuming you are not buffering output (which is the default), then the first time you send any output to the browser using echo or print or just content outside of the PHP tags, the first thing PHP does is send all of the headers, then it sends the output. So the headers are already sent. That means if you send output then try to send another header that won't work because all of the headers for that response have already been sent.The way most people structure their PHP pages that contain HTML is to separate the two. Have all of your PHP processing on the top of the script, before any HTML, then the HTML. Don't put your code to check if a form was submitted and process the form right in the middle of the HTML code, put that at the top of the page before any HTML has gone out. That way you can use PHP to process the form and do other things like redirect or set variables to show error messages or other output farther down the page. Once that processing is finished then you can figure out if you want to redirect or show the HTML or whatever else. If you're going to redirect anyway, there's no reason to send any HTML to the browser.

Link to comment
Share on other sites

I think maybe I understand. So the "<?php echo $partErr;?>", etc. within the form is getting in the way of the php header that's supposed to bring up thankyou.html when the form submitted because it's not in the first block of php at the top of the page?Or do I just need to bring the "header('Location: thankyou.html');" earlier in the script so it comes before the $email_from, $email_body, etc. lines?

Link to comment
Share on other sites

So the "<?php echo $partErr;?>", etc. within the form is getting in the way of the php header that's supposed to bring up thankyou.html when the form submitted because it's not in the first block of php at the top of the page?

That's not getting in the way, that is after the call to the header function.In general, you need to structure your PHP file like this:
<?php// initialize variables$nameErr = '';$emailErr = '';$phoneErr = '';// etc        if ($_SERVER["REQUEST_METHOD"] == "POST") {  // process the form  // validate the form data  // send the email and redirect if appropriate}// then show the HTML?><!DOCTYPE html><html>...
Your PHP processing goes on top, your HTML code goes on bottom. Your HTML code can use the variables that were defined earlier in the PHP part, but the part that has the HTML should not have a bunch of large PHP chunks trying to do things like processing forms or redirecting. Put that stuff on top. By the time your PHP code finishes you should not have outputted anything, you output your page after the PHP is finished. You shouldn't have any echo statements on top. The only PHP code that should appear in the HTML part are the echo statements to print the variables that you set earlier, like the error messages.
  • Like 1
Link to comment
Share on other sites

Try this code .....

 

Mainpage : EmailUs.html

 

<html><head>

<script type="text/javascript" src = "Validation.js"></script>
</head>
<body>
<div>
<center><p><form name="HelpDesk" method = "post" action = "mailTo.php" onsubmit="return validation()">
<table width="36%" border="0" cellpadding="3" cellspacing="3" align="center"><tr><td height="15" align="right" >
Contact No.</td><td><input name="txtPhone" maxlength="15" type="text" /></td></tr><tr><td height="15" align="right" >Email id</td><td><input type='text' name='txtEmail'/></td></tr><tr><td height="15" align="right" >Query</td><td><textarea name="txtDescription" rows="5" cols="30" maxlength="500" alt="write your query here"></textarea></td></tr></table>
<input type="submit" value="Submit"> <input type="reset" name="reset" value="Reset">
</form></p></center>
</div>
</body>
</html>
Validation page : Validation.js
// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function trim(s)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not a whitespace, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (c != " ") returnString += c;
}
return returnString;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf© == -1) returnString += c;
}
return returnString;
}
function checkInternationalPhone(strPhone){
var bracket=3
strPhone=trim(strPhone)
if(strPhone.indexOf("+")>1) return false
if(strPhone.indexOf("-")!=-1)bracket=bracket+1
if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
var brchr=strPhone.indexOf("(")
if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}
function validation()
{
var txtForm=document.HelpDesk;
var Phone=txtForm.txtPhone;
var email = txtForm.txtEmail;
var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if ((Phone.value==null)||(Phone.value==''))
{
alert("Please Enter your Phone Number")
Phone.focus();
return false;
}
else if (checkInternationalPhone(Phone.value)==false)
{
alert("Please Enter a Valid Phone Number")
Phone.value="";
Phone.focus();
return false;
}
else if ((email.value==null)||(email.value==''))
{
alert('Please provide a valid email address');
email.focus();
return false;
}
else if (!filter.test(email.value))
{
alert('Please provide a valid email address');
email.value="";
email.focus();
return false;
}
else if(txtForm.txtDescription.value=='')
{
alert(" Please write your query");
txtForm.txtDescription.focus();
return false;
}
}
Targetpage: EmailTo.php
<?PHP
$email = "desired email id"; // write ur email id here
$strTo = $email;//$_POST["txtTo"];
$strSubject = " Sender id : ".$_POST["txtEmail"];
$strMessage = "<b>Query : -</b> ".nl2br($_POST["txtDescription"]);
//*** Uniqid Session ***//
$strSid = md5(uniqid(time()));
$strHeader = "";
$strHeader .= "From: ".$_POST["txtPhone"]."<".$_POST["txtEmail"].">nReply-To: ".$_POST["txtPhone"]."";
$strHeader .= "MIME-Version: 1.0n";
$strHeader .= "Content-Type: multipart/mixed; boundary="".$strSid.""nn";
$strHeader .= "This is a multi-part message in MIME format.n";
$strHeader .= "--".$strSid."n";
$strHeader .= "Content-type: text/html; charset=utf-8n";
$strHeader .= "Content-Transfer-Encoding: 7bitnn";
$strHeader .= $strMessage."nn";
$flgSend = @mail($strTo,$strSubject,null,$strHeader); // @ = No Show Error //
if($flgSend)
{
?>
<script>
alert("message has been sent successfully..!");
window.location.href = 'http://yor web page'; // put ur URL
</script>
<?PHP
}
else
{
?>
<!-- if message sending failed then below message will be displayed-->
<script>
alert("message sending failed..");
window.location.href = 'http://your web page URL';
</script>
<?PHP
}
?>

 

Link to comment
Share on other sites

Hmm, I see. I'll have to edit that a fair bit to be relevant to the website I'm working on but that could work. I was hoping there would be a simple solution but it seems not, so I'll give that a shot.

Link to comment
Share on other sites

Hmm, I kinda need a lot more to the enquiry form then what your code provides srinivas g. And to edit my code to match that involves basically complete re-writing it. Is there really no simple solution that doesn't involve rewriting the whole thing just to get the form to say "thank you" when submitted? It doesn't need to be an actual page redirect, just anything to show the customer that their enquiry was successfully submitted.This is the whole code for the page currently, not just the relevant parts. Everything seems to work as intended with the only exception being that nothing notifies the customer when they successfully submit the form with all the required details.

<!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>Speedy Spares Australia</title><style type="text/css"><!--body {	font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;	background: #4E5869;	margin: 0;	padding: 0;	color: #000;	background-color: #006699;	background-image: url(images/background.jpg);	background-repeat: repeat;}/* ~~ Element/tag selectors ~~ */ul, ol, dl { /* Due to variations between browsers, it's best practices to zero padding and margin on lists. For consistency, you can either specify the amounts you want here, or on the list items (LI, DT, DD) they contain. Remember that what you do here will cascade to the .nav list unless you write a more specific selector. */	padding: 0;	margin: 0;}h1, h2, h3, h4, h5, h6, p {	margin-top: 0;	 /* removing the top margin gets around an issue where margins can escape from their containing div. The remaining bottom margin will hold it away from any elements that follow. */	padding-right: 15px;	padding-left: 15px; /* adding the padding to the sides of the elements within the divs, instead of the divs themselves, gets rid of any box model math. A nested div with side padding can also be used as an alternate method. */}a img { /* this selector removes the default blue border displayed in some browsers around an image when it is surrounded by a link */	border: none;}/* ~~ Styling for your site's links must remain in this order - including the group of selectors that create the hover effect. ~~ */a:link {	color:#000099;	text-decoration: none; /* unless you style your links to look extremely unique, it's best to provide underlines for quick visual identification */}a:visited {	color: #0066FF;	text-decoration: none;}a:hover, a:active, a:focus { /* this group of selectors will give a keyboard navigator the same hover experience as the person using a mouse. */	text-decoration: none;}/* ~~ this container surrounds all other divs giving them their percentage-based width ~~ */.container {	width: 80%;	max-width: 960px;/* a max-width may be desirable to keep this layout from getting too wide on a large monitor. This keeps line length more readable. IE6 does not respect this declaration. */	min-width: 960px;/* a min-width may be desirable to keep this layout from getting too narrow. This keeps line length more readable in the side columns. IE6 does not respect this declaration. */	background: #FFF;	margin: 0 auto; /* the auto value on the sides, coupled with the width, centers the layout. It is not needed if you set the .container's width to 100%. */}/* ~~the header is not given a width. It will extend the full width of your layout. It contains an image placeholder that should be replaced with your own linked logo~~ */.header {	background: #ffffff;}/* ~~ This is the layout information. ~~ 1) Padding is only placed on the top and/or bottom of the div. The elements within this div have padding on their sides. This saves you from any "box model math". Keep in mind, if you add any side padding or border to the div itself, it will be added to the width you define to create the *total* width. You may also choose to remove the padding on the element in the div and place a second div within it with no width and the padding necessary for your design.*/.content {	padding: 10px 0;}/* ~~ This grouped selector gives the lists in the .content area space ~~ */.content ul, .content ol { 	padding: 0 15px 15px 40px; /* this padding mirrors the right padding in the headings and paragraph rule above. Padding was placed on the bottom for space between other elements on the lists and on the left to create the indention. These may be adjusted as you wish. */}/* ~~ The footer ~~ */.footer {	padding: 10px 0;	background: #6F7D94;}/* ~~ miscellaneous float/clear classes ~~ */.fltrt {  /* this class can be used to float an element right in your page. The floated element must precede the element it should be next to on the page. */	float: right;	margin-left: 8px;}.fltlft { /* this class can be used to float an element left in your page. The floated element must precede the element it should be next to on the page. */	float: left;	margin-right: 8px;}.clearfloat { /* this class can be placed on a <br /> or empty div as the final element following the last floated div (within the #container) if the #footer is removed or taken out of the #container */	clear:both;	height:0;	font-size: 1px;	line-height: 0px;}.blueheader {	color: #00C;}a:hover {	text-decoration: underline;}a:active {	text-decoration: none;}body,td,th {	font-family: Tahoma, Geneva, sans-serif;}.redasterisk {	color: #F00;}.container .content table tr td form h6 .error {	color: #F00;}--></style><script type="text/javascript">function MM_swapImgRestore() { //v3.0  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;}function MM_preloadImages() { //v3.0  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}}function MM_findObj(n, d) { //v4.01  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);  if(!x && d.getElementById) x=d.getElementById(n); return x;}function MM_swapImage() { //v3.0  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}}</script></head><body onload="MM_preloadImages('images/button-quote-on.jpg','images/button-breakdown-on.jpg','images/button-service-on.jpg','images/button-tradeaccount-on.jpg','images/button-home-on.jpg','images/button-specials-on.jpg','images/button-enquiries-on.jpg','images/button-catalogues-on.jpg','images/button-references-on.jpg','images/button-contact-on.jpg')"><?php// define variables and set to empty values$nameErr = $emailErr = $partErr = $phoneErr = "";$name = $email = $part = $comments = $model = $brand = $phone = $contact_method = $product = $breakdown = "";$isError = false;if ($_SERVER["REQUEST_METHOD"] != "POST") {$isError = true;}else {	  if (empty($_POST["name"])) {	  $isError = true;    $nameErr = "Name is required";  } else {  $name = test_input($_POST["name"]);      // check if name only contains letters and whitespace    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {      $nameErr = "Only letters and white space allowed";     }  }      if (empty($_POST["email"])) {		$isError = true;    $emailErr = "Email is required";  } else {  $email = test_input($_POST["email"]);      // check if e-mail address is well-formed    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {      $emailErr = "Invalid email format";     }  }  	if (empty($_POST["phone"])) {		$isError = true;    $contact_methodErr = "Phone number is required";  } else {    $phone = test_input($_POST["phone"]);  }    $contact_method = test_input($_POST["contact_method"]);  $brand = test_input($_POST["brand"]);  $product = test_input($_POST["product"]);  $model = test_input($_POST["model"]);  $breakdown = test_input($_POST["breakdown"]);      if (empty($_POST["part"])) {	   $isError = true;    $partErr = "Part number or description is required";  } else {  $part = test_input($_POST["part"]);  }    $comments = test_input($_POST["comments"]);  }    function test_input($data) {  $data = trim($data);  $data = stripslashes($data);  $data = htmlspecialchars($data);  return $data;}// Function to validate against any email injection attemptsfunction IsInjected($str){  $injections = array('(n+)',              '(r+)',              '(t+)',              '(%0A+)',              '(%0D+)',              '(%08+)',              '(%09+)'              );  $inject = join('|', $injections);  $inject = "/$inject/i";  if(preg_match($inject,$str))    {    return true;  }  else    {    return false;  }} //Validate firstif(IsInjected($email)){	$isError = true;    echo "Bad email value!";    exit;}if(!$isError){		$email_from = 'sales@speedyspares.com';//<== update the email address		$email_subject = "Online Enquiry";		$email_body = '<html><body>';		$email_body .= '<table rules="all" style="border-color: #666;" cellpadding="10">';		$email_body .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . $name = $_POST["name"] . "</td></tr>";		$email_body .= "<tr><td><strong>Email:</strong> </td><td>" . $email = $_POST["email"] . "</td></tr>";		$email_body .= "<tr><td><strong>Phone:</strong> </td><td>" . $phone = $_POST["phone"] . "</td></tr>";		$email_body .= "<tr><td><strong>Preferred Method of Contact:</strong> </td><td>" . $contact_method = $_POST[	"contact_method"] . "</td></tr>";		$email_body .= "<tr><td><strong>Brand:</strong> </td><td>" . $brand = $_POST["brand"] . "</td></tr>";		$email_body .= "<tr><td><strong>Product:</strong> </td><td>" . $product = $_POST["product"] . "</td></tr>";		$email_body .= "<tr><td><strong>Model:</strong> </td><td>" . $model = $_POST["model"] . "</td></tr>";		$email_body .= "<tr><td><strong>Breakdown Required:</strong> </td><td>" . $breakdown = $_POST["breakdown"] . "</td></tr>";		$email_body .= "<tr><td><strong>Part:</strong> </td><td>" . $part = $_POST["part"] . "</td></tr>";		$email_body .= "<tr><td><strong>Comments:</strong> </td><td>" . $comments = $_POST["comments"] . "</td></tr>";		$email_body .= "</table>";		$email_body .= "</body></html>";    		$to = "sales@speedyspares.com";//<== update the email address		$headers = "From: $email_from rn";		$headers .= "Reply-To: $email rn";		$headers .= "MIME-Version: 1.0rn";		$headers .= "Content-Type: text/htmlrn";		//Send the email!		mail($to,$email_subject,$email_body,$headers);		//done. redirect to thank-you page.		header('Location: thankyou.html');}  ?><div class="container">  <div class="header"><!-- end .header -->    <div align="center">            <table width="200" border="0" align="center" cellpadding="0" cellspacing="0">        <tr>          <td rowspan="3"><a href="index.html"><img src="SSLogoimage.gif" title="Speedy Spares Australia" width="120" height="120" /></a></td>          <td height="35" valign="baseline"> </td>        </tr>        <tr>          <td valign="baseline"><a href="index.html"><img src="SSLogotext.gif" title="Speedy Spares Australia" width="530" height="50" /></a></td>        </tr>        <tr>          <td valign="baseline"><h5 align="center" class="blueheader"><strong>Distributor of Electronic Components, Spare Parts & Accessories</strong></h5></td>        </tr>      </table><div class="menu">  <table border="0">  <tr>    <td><a href="index.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('button-home','','images/button-home-on.jpg',1)"><img src="images/button-home.jpg" title="Go back to the front page" name="button-home" width="155" height="46" border="0" id="button-home" /></a></td>    <td><a href="specials.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('button-specials','','images/button-specials-on.jpg',1)"><img src="images/button-specials.jpg" title="See our current sales!" name="button-specials" width="155" height="46" border="0" id="button-specials" /></a></td>    <td><a href="enquiries.php" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('button-enquiries','','images/button-enquiries-on.jpg',1)"><img src="images/button-enquiries.jpg" title="Ask us about a part or get a quote!" name="button-enquiries" width="155" height="46" border="0" id="button-enquiries" /></a></td>    <td><a href="catalogues.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('button-catalogues','','images/button-catalogues-on.jpg',1)"><img src="images/button-catalogues.jpg" title="See our available catalogues!" name="button-catalogues" width="155" height="46" border="0" id="button-catalogues" /></a></td>    <td><a href="references.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('button-references','','images/button-references-on.jpg',1)"><img src="images/button-references.jpg" title="Need something we don't supply? Go here!" name="button-references" width="155" height="46" border="0" id="button-references" /></a></td>    <td><a href="contact.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('button-contact','','images/button-contact-on.jpg',1)"><img src="images/button-contact.jpg" title="Give us a call, send us a email or see us in person!" name="button-contact" width="155" height="46" border="0" id="button-contact" /></a></td>  </tr></table>      </div>  </div>  </div>  <div class="content">    <h3><p align="center">Parts Enquiry</p>    </h3>    <div align="center">      <table border="1" cellpadding="0" cellspacing="0">        <tr>          <td bgcolor="#6699FF"><div align="center">            <h5><br />              You can use the form below to request Price & Availability of parts & accessories<br />              or a Breakdown of parts for a wide range of devices.<br />              Please provide as much information as possible about your device or the parts you require<br />              so that we can better assist with your enquiry.</h5>          </div></td>        </tr>      </table>    </div>    <table width="100%" border="0" cellpadding="5" cellspacing="5">      <tr>        <td bgcolor="#CCCCCC"><form method="post" name="enquiry-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">        <h6><strong><span class="redasterisk">*</span></strong>denotes a required field</h6>        <h6>Name:<span class="error">* <?php echo $nameErr;?></span><br>          <input name="name" type="text" size="50">          <br>          E-mail:<span class="error">* <?php echo $emailErr;?></span><br>          <input name="email" type="text" size="50">          <br>          Phone:<span class="error">* <?php echo $phoneErr;?></span><br>          <input name="phone" type="text" size="50">          <br />          Preferred Contact Method:<br />          <input type="radio" name="contact" value="email" />          Email          <input type="radio" name="contact" value="phone" />          Phone          <br />          Brand:<br>          <select name="brand">            <option value="Sony">SONY</option>            <option value="Sharp">SHARP</option>            <option value="Hills">HILLS</option>            <option value="Other">OTHER</option>            </select><br />          Product:<br>          <select name="product">            <option value="TV">TV/PROJECTOR</option>            <option value="VIDEO">HOME VIDEO/DVD/BLU-RAY</option>            <option value="AUDIO">HOME AUDIO/THEATRE SYSTEM</option>            <option value="CAMERA">DIGITAL STILL CAMERA</option>            <option value="CAMCORDER">VIDEO CAMERA/CAMCORDER</option>            <option value="VAIO">PERSONAL COMPUTER (VAIO)</option>            <option value="EREADER">eBOOK READER</option>            <option value="PAUDIO">PERSONAL AUDIO</option>            <option value="CAUDIO">CAR AUDIO</option>            <option value="FRIDGE">REFRIDGERATOR</option>            <option value="MICROWAVE">MICROWAVE</option>            <option value="OTHER">OTHER</option>            </select><br />          Model :<br /><em>(eg. KDL-46HX800)</em><br>          <input type="text" name="model" size="50">          <br />          <input type="checkbox" name="breakdown" value="Yes" />          Request Breakdown<br />          Part number/description:<span class="error">* <?php echo $partErr;?></span><br /><em>(e.g. UWA-BR100 Wi-fi Adaptor)</em><br />          <input type="text" name="part" size="50">          <br>          Comments:<br>          <textarea name="comments" cols="50" rows="5">Please supply any additional information that may assist with your enquiry. (color/size/location etc.)</textarea>          <br />          (Please do not use this form for submission of credit card information)</h6>          <h5>             <input type="submit" name="submit" value="Submit">            <input type="reset" name="reset" value="Reset">          </h5>        </form></td>        <td bgcolor="#999999"><h6 align="center">If you are having trouble locating the model number on your product<br />            please use the link below to assist<br />            <a href="http://esupport.sony.com/US/p/support-info.pl?info_id=264" target="_new">http://esupport.sony.com/US/p/support-info.pl?info_id=264</a></h6>          <h6 align="center">Speedy Spares treats the privacy of our customers very seriously and does not share the information provided by our customers to any third parties. We may collect some information relevant to an enquiry/order but will delete any collected information upon request or at the completion of the order unless otherwise requested.</h6><p> </p>        <p> </p>        <p> </p></td>      </tr>    </table>  <!-- end .content --></div>  <div class="footer">    <table width="100%" border="0">      <tr>        <td width="640"><h6>Speedy Spares Pty. Ltd.<br />          451 Macaulay Rd<br />          Kensington VIC 3031<br />          Ph: (03) 9376 1333 Fax: (03) 9376 7110<br />        Email: sales@speedyspares.com </h6></td>        <td width="320" valign="top"><div align="center">          <h5><a href="index.html">Home</a><br />            <a href="specials.html">Specials</a><br />            <a href="enquiries.html">Enquiries</a></h5>        </div></td>        <td width="320" valign="top"><div align="center">          <h5><a href="catalogues.html">Catalogues</a><br />            <a href="references.html">References</a><br />            <a href="contact.html">Contact Us</a></h5>        </div></td>      </tr>      <tr>      <td colspan="3"><div align="center">        <h6>© Copyright 2003-2014: Speedy Spares Pty Ltd. All rights reserved. Trademarks and brand names on this site are the property of their respective owners and unless indicated are used solely to describe models for which parts may be suitable.</h6>      </div></td>      </tr>    </table>    <!-- end .footer --></div><!-- end .container --></div></body></html>

I used to have the thankyou redirect working, but I've changed... something in the past 5-10 steps that makes the redirect no longer work.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...