Welcome Guest!

If you do not have an account yet on The Web Squeeze forums, please Register! It’s FREE and there are many benefits:

  • Receive Fast Advice
  • Learn Programming Languages
  • Get Professional Website Reviews
  • Quick Troubleshooting Assistance

> Contact Help

This is a discussion on Contact Help, within the PHP section. This forum and the thread "Contact Help" are both part of the Programming Your Website category.

 
Reply to this topicStart new topic
> Contact Help
unitedcraig
post Jun 26 2008, 04:45 PM
Post #1


Squeeze Machine
Group Icon

Posts: 560
Joined: 14-February 08
From: Stockport


For a change i need some help lol wink.gif

Contact Page
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<?php $page = 'contact'; ?>
<head>
<title>Elektro GIBSON - Contact</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="Elektro Gibson is a highly recommended and skilled Electricians company, servicing both commercial
and private client, based in M&uuml;nchem, Germany." />
<meta name="keywords" content="Electrician, Electrical Installer, M&uuml;nchen, Germany, cheap electrician, light fittings, complete rewire, speaker systems, skilled, expert, advice" />

</head>

<body id="top">

<div id="container">


<div id="branding">
<img src="i/header_<?php echo(rand(1,4)); ?>.png" alt="Welcome to Elektro Gibson, Electrical Engineer based in Munich, Germany" title="Elektro Gibson - Electrical Engineer, Electrical Installer based in Munich, Germany" />

<h1><a href="#" title="Phil Gibson - Electrician, Electrical Engineer, Electrical Installer based in Munich, Germany">Phil Gibson - Electrician, Electrical Engineer, Electrical Installer based in Munich, Germany</a></h1>

<p><q>Expert work, Electrical Engineering, M&uuml;nchen, Deutschland, highly reccommended, cheap electrician, quality work.</q></p>

</div>

<?php include("nav.php"); ?>

<hr />

<div id="content">
<div id="content-main">


<h2>Contact</h2>

<div>
<form method="post" action="contactForm.php" enctype="multipart/form-data"><div>

<!-- Let's get their name //-->

<select name="title">
<option value="mr">Mr</option>
<option value="mrs">Mrs</option>
<option value="miss">Miss</option>
<option value="ms">Ms</option>
</select>





First Name:

<input type="text" name="firstname" />



Surname:

<input type="text" name="lastname" />




Email address:

<input type="text" name="email" />



Phone number:

<input type="text" name="phone" />




How did you hear about us?


<select name="source">
<option value="searchengine">Search Engine</option>
<option value="phonedirectory">Phone Directory</option>
<option value="personal">Personal Recommendation</option>
</select>





What service(s) are you interested in?

(Tick all that apply)



<input type="checkbox" name="services[]" value="wire" />
Wiring (Interior/Exterior)

<input type="checkbox" name="services[]" value="solar" />
Solar Installation

<input type="checkbox" name="services[]" value="sound" />
Sound Systems

<input type="checkbox" name="services[]" value="lights" />
Lighting features

<input type="checkbox" name="services[]" value="gens" />
Generator Installations

<input type="checkbox" name="services[]" value="other" />
Other (please specify)





Other Comments:



<textarea rows="10" cols="40">
Message.....
</textarea>





<input type="submit" name="submit" value="Send!" />




</div></form> </div>

</div>

<div id="content-sub">

<h2>Details</h2>
<ul>
<li>Elektroinstallation</li>
<li>Riezlerweg 46</li>
<li>80997 M&uuml;nchen</li>
<li>Tel: (089) 1434 7490</li>
<li>Fax: (089) 1434 6023</li>
<li>Mobil: 0172/821 0755</li>
<li>&nbsp;</li>
<li><a href="contact.php">Contact</a></li>
</ul>

</div>

</div>

<hr />

<div id="nav-supp">
<p><a href="java script:scroll(0,0);">Back to Top</a> </p>
</div>

<div id="siteinfo">
<p>Valid <a href="http://validator.w3.org/check/referer" title="Validate this document">XHTML</a>, <a href="http://jigsaw.w3.org/css-validator/check/referer" title="Validate this CSS">CSS</a> | Site design by <a href="http://www.craigmoran.co.uk" title="Site designed by Craig Moran">Craig Moran</a></p>
</div>

</div>


</body>
</html>


The PHP


CODE
<?php
/***Code created by Luke <rakuli> Dingle for use on www.thewebsqueeze.com
This script may be modified and used but is provided as is without warranty or guarantee.

It is not mandatory but a link back to http://www.openthource.com would be cool
Have fun! */

/**** Some configurable variables, will put them up the top here so I don't hurt my back bending down in the code to get them later****/

$returnURL = 'contacterror.php'; // The url to send the user back to if something went wrong
$successURL = 'yes.php'; // The url to send the user to if all goes well

$allowedReferer = array($returnURL, 'http://www.craigmoran.co.uk/'); // What URL's would you like to allow to use this script? If the form is sent from elsewhere we can givem the boot
$arrivalMethod = 'post'; // What method will the form be sent using? Choice of 'get', 'post' or 'request' (request is a combination of get and post variables in case you wanted the option to use both)
$submitName = 'submit'; // What is the name of the submit button?

$Temail = 'unitedreds@hotmail.co.uk'; // Change it to anything you like -- is where the email will be sent to
$TemailBcc = ''; // If you want to copy anyone in on all emails sent from the form, add them here separated by commas
$Semail = '"Contact Form" <%s>'; // The subject line of the email %s will be used in sprintf() to add the senders email as the "from" contact

$mailerName = 'Website Contact Form'; // Name the x-mailer, sometimes a good idea to emulate a popular email client name to avoid junk filters



$fVars = ($arrivalMethod == 'post') ? $_POST : ($arrivalMethod == 'get' ? $_GET : $_REQUEST); // Store a reference to where the variables are coming from

# First things first, well actually, it's the second thing if you count the conifguration variables above as the first thing
# Check to make sure that the 'submit' button has been sent and has a value -- if not? Send them to the $return URL

if (!isset($fVars[$submitName]) || empty($fVars[$submitName]))
{
header("Location: $returnURL");
exit();
}

# Next, we'll check if the user has submitted this form from one of the allowed referers
# If not, we'll give them a fruit basket and send them on their way

$pattern = str_replace('\|', '|', preg_quote(implode('|', $allowedReferer), '/'));// Implode the referer array into a regex string this|this|this|this


if (!preg_match('/^(' . $pattern . ').*/',$_SERVER['HTTP_REFERER']))
{
header("Location: $returnURL");
exit();
}


// If we didn't receive the correct input from the submit button, we'll send them away straight awa



/*
# This is the array of form fields that PHP is expecting to receive, the structure is as follows

$formInputs = array (formInputName => arrayOfDetails ( 0 => displayed name of field (string),
1 => is element mandatory? (boolean),
2 => allowed values (array(mixed)),
3 => function to call if required (string),
4 => input is an array of values? (boolean),
5 => customised error message (string)
)
)
*/


$formInputs = array('title' => array('Title', true, array('mr', 'mrs', 'miss', 'ms')),
'firstname' => array('First Name', true),
'lastname' => array('Last Name', true),
'email' => array('Email Address', true, 3 => 'check_email', 5 => 'Your email address is invalid!'),
'phone' => array('Phone Number', false, 3 => 'ctype_digit', 5 => 'Phone field may only contain numbers'),
'source' => array('How did they hear about us?', false, array('searchengine', 'phonedirectory', 'personal')),
'services' => array('Services required', true, array('wire', 'solar','sound', 'lights', 'gens', 'other'), 4 => true),
);


# It's time to loop through all the values and check that they fit the requirements defined
# in the $formInputs array


$errors = array(); // Sumfins up? Shove it in the $errors array to berate the user with later
$errorMsg = 'Please check that you entered <strong>%s</strong> correctly'; // This is the default, legal department approved standard error message

$messageArray = array(); // This will hold all the parts of the email message as the form fields validate


# So we don't loop through $_POST, $_GET or $_REQUEST varibales unnecessarily, loop through the forminputs array and check each that way
foreach ($formInputs as $pk => $pa)
{

// The first check that will render the input immediately invalid is
// checking against the "is required?" directive of the $formInputs array
if (!isset($fVars[$pk]) && $pa[1] === true)
{
// Is there a custom error? If not, just use the default one

$errors[] = $pa[5] ? $pa[5] : sprintf($errorMsg, $pa[0]);
continue;
}



// This next check is for form fields that have numerous available options
// that have been sent to us as an array.


if ($pa[4] === true && is_array($fVars[$pk]) && count($fVars[$pk])) {

$msg = ''; // As this will be more than just a one-line message, set up the variable to hold the string

// Loop through each value, if there is a list of allowed values
// check that it is in that array, otherwise add all of them to $msg
foreach($fVars[$pk] as $val)
{
$msg .= isset($pa[2]) /* List of allowed values? */ ? in_array($val, $pa[2]) ? "\t\t" . htmlentities($val) . "
\n" : ''
/* No List of defaults */ : "\t\t" . htmlentities($val) . "
\n";
}

// If we've been sent a bung array or an array of useless political rants
// $msg will be empty, this means that it will trigger an error if it is
// a mandatory value
if (!empty($msg))
$messageArray[] = '<strong>' . $pa[0] . "</strong> :
\n\n
" . $msg;
else if ($pa[1] === true)
$errors[] = $pa[5] ? $pa[5] : sprintf($errorMsg, $pa[0]);

continue;

// If the value is not an array and also a mandatory element, this will spark an error message

} else if ($pa[1] === true && $pa[4] === true) {

$errors[] = $pa[5] ? $pa[5] : sprintf($errorMsg, $pa[0]);
continue;
}


// Form fields that have a list of allowed values eg. select elements or radio buttons
// This check ensures the sent value is one of those allowed

if (isset($pa[2]))
{
// Is the value in the array? If yes, add it to the $message array
if (in_array($fVars[$pk], $pa[2]))
{
$messageArray[] = '<strong>' . $pa[0] . '</strong> : ' . htmlentities($fVars[$pk]);

// Oh no!!, it's just some crazy sales pitch from an entrepeneurial spammer, that means error message time
// Only if its a mandatory value though
} else if ($pa[1] === true)
$errors[] = $pa[5] ? $pa[5] : sprintf($errorMsg, $pa[0]);

continue;
}

// Now we're dealing with values typed in by the user -- gasp!!
// If we trim the value of whitespace, we can see if we've
// just been sent a string of spaces
$fVars[$pk] = trim($fVars[$pk]);

if (empty($fVars[$pk]) && $pa[1] === true)
{
// Mandatory value? Error it
$errors[] = $pa[5] ? $pa[5] : sprintf($errorMsg, $pa[0]);
continue;

// Empty but not mandatory? Just turn the other cheek
} else if (empty($fVars[$pk]))
continue;



// If this is a value we would like to perform an additional check on
// via a callback function (which returns true for a good value and false for a bad one
if (isset($pa[3]))
{

if ($pa[3]($fVars[$pk]))
// Nice one brudda! Add it to the message
$messageArray[] = '<strong>' . $pa[0] . '</strong> : ' . htmlentities($fVars[$pk]);

// Oh? I guess that you have a dodgy character in there somewhere so if this is a mandatory value
// You is gonna get an error message
else if ($pa[1] == true)
$errors[] = sprintf($errorMsg, $pa[0]);

continue;
}

// Yawn!... just a boring old input with no special characteristics -- just add it to the message please.

$messageArray[] = '<strong>' . $pa[0] . '</strong> : ' . htmlentities($fVars[$pk]);

}




# No Errors? Check - $MessageArray has some values? if check, then we can set up the email

if (!count($errors) && count($messageArray))
{

// Take the subject declared above and add the sender's email to it
// If for some reason, this form is not getting an email off the user
// we can ignore it
if (isset($fVars['email']))
$Semail = sprintf($Semail, $fVars['email']);

// Because we are creating a MIME email (HTML & Plain Text) we need to define some boundaries
// To separate the multiple parts of the message...
// Let's do that now and create an outer and inner boundary
$ob = md5(time() . 'masonboundary');
$ib = md5(time() . 'masonboundary2');


$headers = "From: ".$Semail."\n"; // Add the subject (even if it has no sender email address)

if (!empty($TemailBcc)) $headers .= "Bcc: ".$TemailBcc."\n"; // Carbon copy in the required users

if (isset($fVars['email']))
{ // Set the reply to as the user's email (if available)
$headers .= "Reply-To: <". $fVars['email'].">\n";
$headers .= "Return-Path: <" . $fVars['email'] . ">\n";
}
$headers .= 'Date: ' . gmdate('D, d M Y H:i:s') . ' +0000' . "\n"; // Um, what day is it?
$headers .= 'X-Mailer: ' . $mailerName . "\n"; // Set the mailing application name,

$headers .= 'Mime-Version: 1.0' . "\n"; // Multi type MIME -- hoorays
$headers .= 'Content-Type: multipart/alternative; boundary="' . $ob . '"' . "\n"; // Define the boundary
$headers .= 'Content-Transfer-Encoding: 7bit' . "\n";


// Let's start the content.. this is some very sloppy HTML, you can correct if you like

$content = "<title>$Semail</title>\n\n\n";
$content .= "<body style='font-family: verdana; font-size: 9pt;'>\n\n";
$content .= "<h1 style='font-size:1.1em'>Someone Has Contacted you!</h1>\n\n\n";

// loop through the messageArray and add each line to the email

foreach ($messageArray as $msg)
$content .= $msg . "\n\n

";

$content .= "Your Sincerely,\n\n

"; // Be polite and sign off smile.gif
$content .= "Your Website";


$message = strip_tags($content) . "\n" . '--' . $ob . "\n"; // Add the HTML part boundary and start the message


// Plain text first


$message .= 'Content-Type: text/plain; charset=iso-8859-1' . "\n";
$message .= 'Content-Transfer-Encoding: 7bit' . "\n\n";
$message .= strip_tags($content) . "\n" . '--' . $ob . "\n";

// Now the HTML part

$message .= 'Content-Type: text/html; charset=charset=iso-8859-1' . "\n";
$message .= 'Content-Transfer-Encoding: 7bit' . "\n\n";
$message .= $content . "\n" . '--' . $ob . '--';


mail($Temail, $subject, $message, $headers);

// Givem their kudos
header('Location: ' . $successURL);

}

function check_email($email)
{ // First, we check that there's one @ symbol,
// and that the lengths are right.
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}


if (count($errors))
{
?>
<!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>Some Bad Things Went Down</title>
</head>

<body>
<?php
echo '<div style="border: solid 1px red;padding: 2em;">
<h1 style="font-size: 1.2em;">Some Errors Occurred</h1>
<ul>';

foreach ($errors as $err)
echo '<li>', $err, '</li>';

echo '</ul>
<a href="', $returnURL , '" onclick="window.history.back(); return false;">Go Back and try again</a>
</div>';
?>
</body></html>
<?php
}
?>


Sorry about all the code, (we need to get a scrolling code box lol), what happens is whenever i try to send the form it goes straight to the error page. Any thoughts?

Thanks again

Craig
Reason for edit: Add [codebox] tag!


--------------------
Go to the top of the page
 
+Quote Post
unitedcraig
post Jun 28 2008, 04:51 AM
Post #2


Squeeze Machine
Group Icon

Posts: 560
Joined: 14-February 08
From: Stockport


Please help lol


--------------------
Go to the top of the page
 
+Quote Post
Rakuli
post Jun 28 2008, 05:12 AM
Post #3


Squeeze Machine
Group Icon

Posts: 764
Joined: 13-February 08
From: Catching the squeezed drips downunder.


The reason I think is because you have put simply the page that is allowed to arrive (contact.php).

Change $allowedReferer = array($returnURL, 'http://www.craigmoran.co.uk/');

to

$allowedReferer = array( 'http://www.craigmoran.co.uk/');

and make sure that you are viewing http://www.craigmoran.co.uk/contact.php when you fill in the form.

Also, what errors are you gettinG?


--------------------
Luke Dingle . com

Turn Over a Playful Leaf on Web Design -- read about the javascript cat
Go to the top of the page
 
+Quote Post
If you found The Web Squeeze to be helpful, please donate so we can keep this site FREE, FRESH, and fortified with Web Design & Development info!
Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Collapse

> Similar Topics

    Topic Title Replies Topic Starter Views Last Action
No new   40 Rakuli 1,178 16th December 2008 - 12:03 PM
Last post by: Bruno
No New Posts   1 Daniel 187 17th June 2008 - 02:49 PM
Last post by: Jacob
No New Posts 10 Bruno 435 2nd July 2008 - 01:34 PM
Last post by: velo
No New Posts   2 Jasontor 335 6th August 2008 - 02:44 PM
Last post by: Jasontor
No New Posts   2 gribble 287 5th November 2008 - 01:24 PM
Last post by: MikeHopley