Solved

IF statement based on selection from drop down menu

Posted on 2011-02-15
7
301 Views
Last Modified: 2012-05-11
Hi, my site has a contact form that allows customers to send a message. The contact form has a drop down menu which allows the customer to choose from 3 products that they want to enquire about.

I have 3 different email addresses for each product as 3 different administrators are responsible for each product. At the moment the contact form is emailed to all 3 administrators.

How can i change my code below so that if a certain product is selected from the contact form, only the administrator responsible for that product is emailed:

CONTACT FORM

<form name="contact" id="form" action="contact.processor.php" onSubmit="return validate_form(this);" enctype="multipart/form-data" method="post">
         
<div class="form_heading">Name:</div>
<div><input type="text" class="form_input" name="name" size="30" maxlength="35" tabindex="1" /></div>
           
<div class="form_heading">Phone Number:</div>
<div><input type="text" class="form_input" name="phone" size="30" maxlength="20" tabindex="2" /></div>
           
<div class="form_heading">Email:</div>
<div><input type="text" class="form_input" name="email" size="30" maxlength="49" tabindex="3" /></div>
           
<div class="form_heading">Product:</div>
<div>
<select name="product" tabindex="4">
   <option value="All" selected>--- All Products ---</option>
   <option value="Product A">Product A</option>
   <option value="Product B">Product B</option>
   <option value="Product C">Product C</option>
</select>
</div> 
                   
<div><input name="submit" tabindex="5" type="submit" id="submit" value="Send" /> <input type="reset" tabindex="7" name="Reset" value="Reset" /></div>
             
</form>

Open in new window


PHP
<?php
     
        $todayis    = date("l, F j, Y, g:i a") ;
       
        $name       = $_POST['name'];
        $phone      = $_POST['phone'];
        $email      = $_POST['email'];
        $product    = $_POST['product'];
       
        $body = " $todayis [EST] \n
        Name: $name \n
        Phone: $phone \n
        Email: $email \n
        Product Enquiry: $product \n
        ";

$to         = "product-a@gmail.com, product-b@gmail.com, product-c@gmail.com";
$subject    = "Contact Us";
$from       = "From: $email\r\n";

mail($to, $subject, $body, $from);

?>

Open in new window


Thanks in advance...
0
Comment
Question by:oo7ml
7 Comments
 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 175 total points
ID: 34897139
Something like this should do

switch( $product ) {

     case 'Product A':
          $to = "product-a@gmail.com";
          break;

     case 'Product B':
          $to = "product-b@gmail.com";
          break;

     case 'Product C':
          $to = "product-c@gmail.com";
          break;

     default:
          // Assume that somebody is hacking the form
          exit;
}


// $to         = "product-a@gmail.com, product-b@gmail.com, product-c@gmail.com";

Open in new window


Insert just before the existing $to (you will notice I've commented it out). I could have used multiple IF statements but a SWITCH is nice and clear and the DEFAULT clause eliminates the possiblity of people fiddling with the form. Always assume that somebody will hack it - or try to
0
 
LVL 2

Expert Comment

by:johnwarde
ID: 34897216
For expansion purposes (i.e. more then three products in the future) I would use an associative array (Ideally you would use a relational database for this but that may be overkill for you at this stage).

For a quick solution, insert the following at the top of your php code i.e. line 2 ...

$prod_info = array(
    'Product A' => 'product-a@gmail.com',
    'Product B' => 'product-b@gmail.com',
    'Product C' => 'product-c@gmail.com'
    );

And change line 17 (as above) to ...

$to = $prod_info[$_POST['product']];

0
 

Author Comment

by:oo7ml
ID: 34897354
Would it be a bad idea to directly insert the email addresses into the drop down menu:

   <option value="emaila">Product A</option>
   <option value="emailb">Product B</option>
   <option value="emailc">Product C</option>

as the email addresses are listed on my contact page
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 2

Assisted Solution

by:johnwarde
johnwarde earned 175 total points
ID: 34897560
For a more ideal solution you might use product codes (you can choose whether or not your user will see these, this solution does not show product codes to the user) and you can also store extra information with this solution.  In my previous comment I neglected the "All Products" option, I cover it here.

// Put this code in a separate file i.e. products_db.php
<?php
$prod_info = array(
    'all' => array(
        'name' => '--- All Products ---',
        'email' => 'product-a@gmail.com, product-b@gmail.com, product-c@gmail.com',
        'other' => 'All products selected'
        ),
    'prod-a' => array(
        'name' => 'Product A',
        'email' => 'product-a@gmail.com',
        'other' => 'other info for Product A'
        ),
    'prod-b' => array(
        'name' => 'Product B',
        'email' => 'product-b@gmail.com',
        'other' => 'other info for Product B'
        ),
    'prod-c' => array(
        'name' => 'Product C',
        'email' => 'product-c@gmail.com',
        'other' => 'other info for Product C'
        ),
    'prod-d' => array(
        'name' => 'Product D',
        'email' => 'product-d@gmail.com',
        'other' => 'other info for Product D'
        )
    );
?>

Put the following piece of code at the top of your HTML file AND your other PHP file (contact.processor.php)
<?php
include_once 'products_db.php';
?>

In your HTML change lines 14 - 19 to ...
<select name="product" tabindex="4">
<?php
    foreach ($prod_info as $prod) {
?>
   <option value="<?php echo key($prod_info); ?>"><?php echo $prod['name']; ?></option>
<?php
    } // end foreach
?>
</select>


And change line 17 to ...

$to = $prod_info[$_POST['product']]['email];

More info about arrays on ...
http://php.net/manual/en/language.types.array.php

John

0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 34897583
"Would it be a bad idea to directly insert the email addresses into the drop down menu:"

Yes - that would be an atrocious idea, possibly the worst thing you could do. Here is why.....

You put the email into the drop-down and you then use the drop down to send an email to

mail( $_POST['email'],......... etc

I (a malicious hacker) then come along with my spam email which I POST to your form with the email of my choice filled in. Your script then obligingly sends the spam and a week later your inbox is full of bounced spam and your server is blaclisted as an open spam relay.

Don't do it! Never, ever, ever, ever, ever trust information coming from a form. Always assume it is tainted, always assume it needs cleaning before use or storage in a database.
0
 
LVL 2

Expert Comment

by:johnwarde
ID: 34897668

Would it be a bad idea to directly insert the email addresses into the drop down menu:

   <option value="emaila">Product A</option>
   <option value="emailb">Product B</option>
   <option value="emailc">Product C</option>

as the email addresses are listed on my contact page
If you did this spammers would be able to harvest your email addresses (including the ones on your contact page).  

The convention these days is not to have any email addresses on your web site at all and use a form to allow your customers contact you.

John
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 150 total points
ID: 34899296
I have no problem publishing an email address on my web sites.  I use a simple obscure function to avoid spammers harvesting, but it does not really matter.  The spammers already have your email address.  My rate of false negatives on spam with GMail has been about 1 penetration per 100,000 messages.

BTW, this sequence makes your script an open-relay for spam.  The $email variable could contain a BCC list, etc.

$email      = $_POST['email'];
$from       = "From: $email\r\n";
mail($to, $subject, $body, $from);

You probably want to validate the email that the client put into the form with something like the code snippet.

<?php // RAY_email_validation.php
error_reporting(E_ALL);


// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
function check_valid_email($email)
{
    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    // MAN PAGE: http://us3.php.net/manual/en/intro.filter.php
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }
    // IF LOWER-LEVEL PHP, WE CAN CONSTRUCT A REGULAR EXPRESSION
    else
    {
        $regex
        = '/'                       // START REGEX DELIMITER
        . '^'                       // START STRING
        . '[A-Z0-9_-]'              // AN EMAIL - SOME CHARACTER(S)
        . '[A-Z0-9._-]*'            // AN EMAIL - SOME CHARACTER(S) PERMITS DOT
        . '@'                       // A SINGLE AT-SIGN
        . '([A-Z0-9][A-Z0-9-]*\.)+' // A DOMAIN NAME PERMITS DOT, ENDS DOT
        . '[A-Z\.]'                 // A TOP-LEVEL DOMAIN PERMITS DOT
        . '{2,6}'                   // TLD LENGTH >= 2 AND =< 6
        . '$'                       // ENDOF STRING
        . '/'                       // ENDOF REGEX DELIMITER
        . 'i'                       // CASE INSENSITIVE
        ;
        if (!preg_match($regex, $email)) return FALSE;
    }

    // FILTER_VAR OR PREG_MATCH DOES NOT TEST IF THE DOMAIN IS ROUTABLE
    $domain = explode('@', $email);

    // MAN PAGE: http://us3.php.net/manual/en/function.checkdnsrr.php
    if ( checkdnsrr($domain[1],"MX") || checkdnsrr($domain[1],"A") ) return TRUE;

    // EMAIL IS NOT ROUTABLE
    return FALSE;
}


// DEMONSTRATE THE FUNCTION IN ACTION
$e = '';
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (check_valid_email($e))
    {
        echo "<br/>VALID: $e \n";
    } else
    {
        echo "<br/>BOGUS: $e \n";
    }
}

// END OF PROCESSING - PUT UP THE FORM
$form = <<<ENDFORM
<form method="get">
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" value="$e" />
<input type="submit" />
</form>
ENDFORM;

echo $form;

Open in new window

0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Envision that you are chipping away at another e-business site with a team of pundit developers and designers. Everything seems, by all accounts, to be going easily.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now