I'm using a simple php mailer for my sites contact form. I have a form asking first for their subject of contact, and if they select a spesific option, then the recipient selection will fade in and you can select the recipient you want to use. BUT. I don't want to write the email addresses in the code, because of spam. So I'm trying to achieve this via php variables.
My mailer looks like this:
<?php
$var1="xxx@gmail.com";
$var2="xxx@gmail.com";
$to = "$_POST[kohde]";
$subject = "$_POST[asia]";
$message = "
$_POST[tiedot]
$_POST[nimi]
$_POST[email]
$_POST[puhelin]
IP-osoite: $_POST[ip] ";
$from = "xxx.fi";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
But using the variable names as is in value wont work. So how would I select the email to use with the option without hard coding the email to the option value?
<select name="kohde" style="width:233px;" >
<option value="$var1">xxx.fi</option>
<option value="$var">Sivun tekijälle</option>
</select>
I would do it this way...
Use this PHP to get the $to address:
$goodAddresses = array(1 => 'a@x.com', 2 => 'b@x.com');
$to = 'default@x.com';
if(isset($goodAddresses[$_POST['kohde']])) {
$to = $goodAddresses[$_POST['kohde']];
}
And change the values of your select options in our html file to match the array keys in the PHP:
<select name="kohde" style="width:233px;" >
<option value="1">xxx.fi</option>
<option value="2">Sivun tekijälle</option>
</select>
Your first code should be this:
<?php
$var1="xxx@gmail.com";
$var2="xxx@gmail.com";
$to = $_POST["kohde"];
$subject = $_POST["asia"];
$message = $_POST["tiedot"] .
$_POST["nimi"] .
$_POST["email"] .
$_POST["puhelin"] .
"IP-osoite:" . $_POST["ip"];
$from = $_POST["kohde"];
$headers = "From:" . $from;
mail($to, $subject, $message, $headers);
?>
You have to put the quotes around the array selectors, within the brackets, not around the whole variable name. Also, you can add the form value as $from
using $_POST["kohde"]
.