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

> Php Form With Some Questions Relevent To Past Questions.

This is a discussion on Php Form With Some Questions Relevent To Past Questions., within the PHP section. This forum and the thread "Php Form With Some Questions Relevent To Past Questions." are both part of the Programming Your Website category.

2 Pages V   1 2 >  
Reply to this topicStart new topic
> Php Form With Some Questions Relevent To Past Questions.
Itsumishi
post May 13 2008, 09:35 PM
Post #1


Squeezing
***

Posts: 78
Joined: 5-March 08
From: Melbourne, Australia


Hi. I wasn't too sure how to describe this in the Topic Title.
Basicly I'm trying to create a form with a few Yes or No answers that lead to further questions.

For example If someone answers Yes to Question 1 then I want them to answer questions 2 through to 4. But I don't want them able to answer questions 5 through to 7 and vice versa. Questions 2-7 are all text response questions.

I then want everyone to answer question 8. If they answer yes to question 8 I want them to answer 8a and 8b. If No, then skip to 9, etc.

I've been scouring around for a while trying to find how to do something like this but it seems a hard topic to do searches on. Can anyone point to any tutorials or give any hints on how to start?

It would be good if once they chose Yes or No the unrelevent questions became inaccesable (greyed out or whatever you want to call it)

This post has been edited by Itsumishi: May 13 2008, 09:44 PM
Go to the top of the page
 
+Quote Post
Antti
post May 14 2008, 12:21 AM
Post #2


Rapid Squeezer
Group Icon

Posts: 307
Joined: 15-February 08
From: Finland


How about doing one centralized form page. That's even more easy if you have only yes-no answer options. Pass the question number as a querystring or post variable. Then on post action check the question number and the answer and "redirect" the user according to your rules. Something like:

CODE
switch ($question)
{
  case 1:
    if ($answer == "yes")
    {
      header("location: questions.php?q=5");
    }
    else if ($answer == "no")
    {
       header("location: questions.php?q=2");
    }
    break;
}


You can think another good and flexible approach to that structure in your code but that's an example how you could do it. Ofcourse you need to store the answers to somewhere, an array in session maybe or straight to the database related to that sessionid (or userid if you have one available). If you store the values to the session then you can store them into database when the user completes all the questions. That way you don't end up with half-filled answers in your database.


--------------------
Go to the top of the page
 
+Quote Post
Itsumishi
post May 14 2008, 08:44 PM
Post #3


Squeezing
***

Posts: 78
Joined: 5-March 08
From: Melbourne, Australia


Hmm. Sorry I'm still very new to PHP. I only half understand what you're saying.
Basicly I've got a basic 5 minute survey and we want the results to be emailed to us. I've already set all that part up to work just following Rakuli's tutorial (which is great by the way Rakuli! thanks for the effort!) but currently people need to fill out all the questions for it to validate. This isn't what we want.

The Survey

If you read through you'll see where it says to skip questions depending on answers etc.

Edit: Ooops, forgot to put the PHP in.

CODE
/**** 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 = 'http://www.dtlawards.com/vfitbsurvey/registrationfail.html'; // The url to send the user back to if something went wrong

$successURL = 'http://www.dtlawards.com/vfitbsurvey/registrationsuccess.html'; // The url to send the user to if all goes well

$allowedReferer = array('http://www.dtlawards.com','http://www.vfitb.com.au'); // 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?

$mailerName = 'Online Contact Form'; // Name the x-mailer

$Temail = 'foodsurvey@ssv.org.au';// Change it to anything you like -- is where the email will be sent to

$TemailBcc = 'foodsurveyadmin@ssv.org.au'; // If you want to copy anyone in on all emails sent from the form, add them here separated by commas

$subject = 'Food Science & Technology Qualifications in the Food Processing Industry' ; // This is the subject of the email.

$Semail = '"Food Survey" <%s>'; // The subject line of the email %s will be used in sprintf() to add the senders email as the "from" contact

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



# 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

$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();

}

/*

# 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', 'Dr')),
'firstname' => array('First Name', true),
'lastname' => array('Last Name', true),
'company' => array('Company',true),
'site' => array('Site', true),
'phone' => array('Contact Number', true, 3 => 'ctype_digit', 5 => 'Phone field may only contain numbers'),
'email' => array('Email', true, 3 => 'check_email', 5 => 'Your email address is invalid!'),
'employ' => array('Do you employ people in the food science and technology area?', true, array('yes', 'no')),
'jobrole' => array('What is the job role they undertake?', true),
'skills' => array('What are the particular skills & knowledge they need for this job?', true),
'qualifications' => array('What qualifications do they have?', false, array('certIVfoodprocessing', 'dipfoodprocessing', 'certIVlabtechniques', 'diplabtech', 'certIVfoodsciencetech', 'dipfoodsciencetech', 'degree', 'other')),
'degree' => array('Degree sepcified', true),
'otherQ1' => array('Other specified', true),
'needskills' => array('Do you have employees with a need for skills & knowledge to be developed in food science and technology?', true, array('yes', 'no')),
'skillsforjob' => array('What are the current qualifications of the employees that need these skills?', true),
'rolechanging' => array('Has, or is the job role changing so that the skills required are also changing?', true, array('yes', 'no')),
'rolechanginghow' => array('What the changes are', true),
'rolechangingskills' => array('What are the new skills', true),
'higherskills' => array('Are there skill needs existing or emerging that may require a qualification at a higher level?', true, array('yes', 'no')),
'higherskillsjobrole' => array('What would their job role be?', true),
'higherskillstasks' => array('What tasks would this worker need to perform?', true),
'higherskillsknowledge' => array('What skills & knowledge would they need?', 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 %s 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[] = '' . $pa[0] . " :
\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[] = '' . $pa[0] . ' : ' . 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[] = '' . $pa[0] . ' : ' . 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[] = '' . $pa[0] . ' : ' . htmlentities($fVars[$pk]);

}

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;
}

# 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 = "\n\n\n";
$content .= "\n\n";
$content .= "<h1 style="font-size: 1.1em;">DTL Awards Registration</h1>\n\n\n";

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

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

";

$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);

}

if (count($errors))
{
?>









echo '
<h1 style="font-size: 1.2em;">Some Errors Occurred</h1>
    ';

    foreach ($errors as $err)
    echo '
  • ', $err, '';

    echo '

Go Back and try again
';
?>

}
?>


This post has been edited by Itsumishi: May 14 2008, 09:01 PM
Go to the top of the page
 
+Quote Post
Antti
post May 15 2008, 12:28 AM
Post #4


Rapid Squeezer
Group Icon

Posts: 307
Joined: 15-February 08
From: Finland


So your whole survey is in one page. Then I would suggest some sort of Javascript where you disable fields depending on what the user answered. Whenever user has answered a question, check out what fields to disable or enable with javascript. This way the whole experience stays very user friendly. Just one option you could go with.


--------------------
Go to the top of the page
 
+Quote Post
Itsumishi
post May 15 2008, 01:24 AM
Post #5


Squeezing
***

Posts: 78
Joined: 5-March 08
From: Melbourne, Australia


Hmm. Javascript you say, another language I'm certainly not familiar with yet but I'll have to look into it tomorrow.

I'm still quite new to the whole web development world (made my first completely terrible table based website last december). I'm slowly learning some of the tricks of HTML and CSS but the PHP and Javascript stuff still confuses the crap out of me.

Basicly I've decided that the disabling of boxes, etc will have to wait a little bit as the deadline to have this form up and running is tomorrow morning (the project was given to me about 4.30 the day before yesterday and I barely had a clue of what to do!).

Anyway I've made some changes to the above form because it was made apparent we needed more space to fill in answers, etc and I didn't want the form looking for answers in every box.

Here's the form now.

CODE
/**** 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 = 'http://www.dtlawards.com/vfitbsurvey/registrationfail.html'; // The url to send the user back to if something went wrong

$successURL = 'http://www.dtlawards.com/vfitbsurvey/registrationsuccess.html'; // The url to send the user to if all goes well

$allowedReferer = array('http://www.dtlawards.com','http://www.vfitb.com.au'); // 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?

$mailerName = 'Online Contact Form'; // Name the x-mailer

$Temail = 'foodsurvey@ssv.org.au';// Change it to anything you like -- is where the email will be sent to

$TemailBcc = 'foodsurveyadmin@ssv.org.au'; // If you want to copy anyone in on all emails sent from the form, add them here separated by commas

$subject = 'Food Science and Technology Qualifications in the Food Processing Industry' ; // This is the subject of the email.

$Semail = '"Food Survey" <%s>'; // The subject line of the email %s will be used in sprintf() to add the senders email as the "from" contact

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



# 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

$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();

}

/*

# 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', 'Dr')),
'firstname' => array('First Name', true),
'lastname' => array('Last Name', true),
'company' => array('Company',true),
'site' => array('Site', true),
'phone' => array('Contact Number', true, 3 => 'ctype_digit', 5 => 'Phone field may only contain numbers'),
'email' => array('Email', true, 3 => 'check_email', 5 => 'Your email address is invalid!'),
'employ' => array('Do you employ people in the food science and technology area?', true, array('yes', 'no')),
);

Jobrole: '.$jobrole;'
Skill: '.$skill;'

$formInputs = array( 'qualifications' => array('What qualifications do they have?', false, array('certIVfoodprocessing', 'dipfoodprocessing', 'certIVlabtechniques', 'diplabtech', 'certIVfoodsciencetech', 'dipfoodsciencetech', 'degree', 'other')),
);

Degree: '.$degree;'
Other: '.$other;'

$formInputs = array( 'needskills' => array('Do you have employees with a need for skills & knowledge to be developed in food science and technology?', true, array('yes', 'no')),
);

Skills for Job: '.$skillsforjob;'

$formInputs = array( 'rolechanging' => array('Has, or is the job role changing so that the skills required are also changing?', true, array('yes', 'no')),
);
Role Changing How: '.$rolechanginghow;'
Role Changing Skills: '.$rolechangingskills;'

$formInputs = array( 'higherskills' => array('Are there skill needs existing or emerging that may require a qualification at a higher level?', true, array('yes', 'no')),
);
Higher Skills Job Role: '.$higherskillsjobrole;'
Higher Skills Tasks: '.$higherskillstasks;'
Higher Skills Knowledge: '.$higherskillsknowledge;'



# 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 %s 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[] = '' . $pa[0] . " :
\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[] = '' . $pa[0] . ' : ' . 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[] = '' . $pa[0] . ' : ' . 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[] = '' . $pa[0] . ' : ' . htmlentities($fVars[$pk]);

}

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;
}

# 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

$Semail $content = "\n\n\n";
$content .= "\n\n";
$content .= "<h1 style="font-size: 1.1em;">Food Science and Technology Qualifications in the Food Porcessing Industry</h1>\n\n\n";

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

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

";

$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);

}

if (count($errors))
{
?>




Error Processing Form




echo '
<h1 style="font-size: 1.2em;">Some Errors Occurred</h1>
    ';

    foreach ($errors as $err)
    echo '
  • ', $err, '';

    echo '

Go Back and try again
';
?>

}
?>


There's the PHP.

I'm not even sure if this is working at the moment. Waiting on the email to come in on the last test I did.
A lot of my work is guesswork as yeah. I'm confused and I need to get somewhere!!
Go to the top of the page
 
+Quote Post
Itsumishi
post May 15 2008, 01:50 AM
Post #6


Squeezing
***

Posts: 78
Joined: 5-March 08
From: Melbourne, Australia


arhh.. That's definately not going to work. Ignore the last post. I'll post again when I've worked out something that's slightly on the right track!

This post has been edited by Itsumishi: May 15 2008, 01:51 AM
Go to the top of the page
 
+Quote Post
Itsumishi
post May 15 2008, 02:23 AM
Post #7


Squeezing
***

Posts: 78
Joined: 5-March 08
From: Melbourne, Australia


Ok. I'm completely stuck. My brain is fried and I need to go home and play some MarioKart or something.
I don't care about the questions disapearing and re-appearing anymore.
I just want to know what code I add in so that when someone completes my form it sends the information from the "textarea" fields in the email.

I've been reading and reading and I just can't think anymore...
Here is my form.

CODE
/**** 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 = 'http://www.dtlawards.com/vfitbsurvey/registrationfail.html'; // The url to send the user back to if something went wrong

$successURL = 'http://www.dtlawards.com/vfitbsurvey/registrationsuccess.html'; // The url to send the user to if all goes well

$allowedReferer = array('http://www.dtlawards.com','http://www.vfitb.com.au'); // 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?

$mailerName = 'Online Contact Form'; // Name the x-mailer

$Temail = 'foodsurvey@ssv.org.au';// Change it to anything you like -- is where the email will be sent to

$TemailBcc = 'foodsurveyadmin@ssv.org.au'; // If you want to copy anyone in on all emails sent from the form, add them here separated by commas

$subject = 'Food Science and Technology Qualifications in the Food Processing Industry' ; // This is the subject of the email.

$Semail = '"Food Survey" <%s>'; // The subject line of the email %s will be used in sprintf() to add the senders email as the "from" contact

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



# 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

$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();

}

/*

# 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', 'Dr')),
'firstname' => array('First Name', true),
'lastname' => array('Last Name', true),
'company' => array('Company',true),
'site' => array('Site', true),
'phone' => array('Contact Number', true, 3 => 'ctype_digit', 5 => 'Phone field may only contain numbers'),
'email' => array('Email', true, 3 => 'check_email', 5 => 'Your email address is invalid!'),
'employ' => array('Do you employ people in the food science and technology area?', true, array('yes', 'no')),
'qualifications' => array('What qualifications do they have?', false, array('certIVfoodprocessing', 'dipfoodprocessing', 'certIVlabtechniques', 'diplabtech', 'certIVfoodsciencetech', 'dipfoodsciencetech', 'degree', 'other')),
'needskills' => array('Do you have employees with a need for skills & knowledge to be developed in food science and technology?', true, array('yes', 'no')),
'rolechanging' => array('Has, or is the job role changing so that the skills required are also changing?', true, array('yes', 'no')),
'higherskills' => array('Are there skill needs existing or emerging that may require a qualification at a higher level?', true, array('yes', 'no')),
);


# 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 %s 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[] = '' . $pa[0] . " :
\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[] = '' . $pa[0] . ' : ' . 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[] = '' . $pa[0] . ' : ' . 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[] = '' . $pa[0] . ' : ' . htmlentities($fVars[$pk]);

}

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;
}

# 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

$Semail $content = "\n\n\n";
$content .= "\n\n";
$content .= "<h1 style="font-size: 1.1em;">Food Science and Technology Qualifications in the Food Porcessing Industry</h1>\n\n\n";

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

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

";

$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);

}

if (count($errors))
{
?>




Error Processing Form




echo '
<h1 style="font-size: 1.2em;">Some Errors Occurred</h1>
    ';

    foreach ($errors as $err)
    echo '
  • ', $err, '';

    echo '

Go Back and try again
';
?>

}
?>


There is my PHP.

I know this won't be hard but right now working out how to use an elevator would seem hard to me.

This post has been edited by Itsumishi: May 15 2008, 02:25 AM
Go to the top of the page
 
+Quote Post
Ryan
post May 15 2008, 02:49 AM
Post #8


Rapid Squeezer
****

Posts: 128
Joined: 14-February 08
From: Hounslow, London


CODE
<?php
if(isset($_POST["submit"])) {
  $subject = stripslashes($_POST["subject"]);
  $message = stripslashes($_POST["message"]);
  $headers = 'From: website@ryanfait.com'."\r\n".'Reply-To: '.$_POST["email"]."\r\n".'X-Mailer: PHP/'.phpversion();

  mail("me@gmail.com", $subject, $message, $headers);
}
?>
<form method="post" action=".">
  <p><label for="email">Email address</label><br />
  <input type="text" id="email" name="email" size="20" value="" /></p>
  <p><label for="subject">Subject</label><br />
  <input type="text" id="subject" name="subject" size="20" value="" /></p>
  <p><label for="message">Message</label><br />
  <textarea id="message" name="message" cols="20" rows="5"></textarea></p>
  <p><input type="submit" name="submit" value="Send the Message" /></p>
</form>


Here's a simplified version of what I use to email form contents.


--------------------
Go to the top of the page
 
+Quote Post
Itsumishi
post May 15 2008, 03:41 AM
Post #9


Squeezing
***

Posts: 78
Joined: 5-March 08
From: Melbourne, Australia


Thanks heaps.
I don't know why but after staring at tutorials all day long and finding none fo them made sense, your code seemed to make sense without even an explination next to it.

Does this look like it will work? Where all the $blahblah's are just parts of my form?

CODE
if(isset($_POST["submit"])) {
$subject = stripslashes($_POST["subject"]);
$message = stripslashes($_POST["message"]);
$headers = 'From: foodsurvey@ssv.org.au'."\r\n".'Reply-To: '.$_POST["email"]."\r\n".'X-Mailer: PHP/'.phpversion();

mail("foodsurveyadmin@ssv.org.au", $title, $fisrtname, $lastname, $company, $site, $phone, $email, $employ, $jobrole, $skills, $qualifications, $degree, $otherQ1, $needskills, $skillsforjob, $rolechanging, $rolechanginghow, $rolechangingskills, $higherskills, $higherskillsjobrole, $higherskillstasks, $higherskillsknowledge, $headers);
}

$formInputs = array( 'title' => array('Title', true, array('Mr', 'Mrs', 'Miss', 'Ms', 'Dr')),
'firstname' => array('First Name', true),
'lastname' => array('Last Name', true),
'company' => array('Company',true),
'site' => array('Site', true),
'phone' => array('Contact Number', true, 3 => 'ctype_digit', 5 => 'Phone field may only contain numbers'),
'email' => array('Email', true, 3 => 'check_email', 5 => 'Your email address is invalid!'),
'employ' => array('Do you employ people in the food science and technology area?', true, array('yes', 'no')),
'qualifications' => array('What qualifications do they have?', false, array('certIVfoodprocessing', 'dipfoodprocessing', 'certIVlabtechniques', 'diplabtech', 'certIVfoodsciencetech', 'dipfoodsciencetech', 'degree', 'other')),
'needskills' => array('Do you have employees with a need for skills & knowledge to be developed in food science and technology?', true, array('yes', 'no')),
'rolechanging' => array('Has, or is the job role changing so that the skills required are also changing?', true, array('yes', 'no')),
'higherskills' => array('Are there skill needs existing or emerging that may require a qualification at a higher level?', true, array('yes', 'no')),
);

?>
Go to the top of the page
 
+