Forum Moderators: coopster

Message Too Old, No Replies

php mail security

php mail security

         

hostanything

10:14 pm on Jan 1, 2009 (gmt 0)

10+ Year Member



Hi, I'm working on a very simple script to handle a small email form. I have validated everything I'm sending to the mail function except $msg (body of the email) and I'm wondering if I need to do this to? Here's my code so far...

<?php

session_start();

if($_SESSION['token'] != $_POST['token']) die('This script may only be called from an allowed form');

// Required fields
if ($_POST['realname'] && $_POST['occupation'] && $_POST['age'] && $_POST['city'] && $_POST['email'] && $_POST['phone'] ) {

// validate the submitted email address
$regex = '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+$';
preg_match("/$regex/i",$email) ? $email = $_POST['email'] : die (' Your email address is not valid. Please use your back button and correct the problem ' );

// validate name
preg_match('/^[\w\s]+$/i',$realname) ? $realname = $_POST['realname'] : die (' Names can only contain letters and spaces ');

// print out all the fields and there data
foreach($_POST as $field => $data) {
if($data !='') {
$msg .= $field.": ".$data ."\n";
}
}

$mailheaders = "From: $realname <$email>\n";
$mailheaders .= "Reply-To: $email\n\n";

if ($_POST['key'] == "4" ¦¦ $_POST['key'] == "four" ) {
mail('myemail@test.com', 'WebPage Appointment Request', $msg, $mailheaders);
Header("Location: thanks.php");
} else {
echo "You did not answer the spambot question to prove you are a real human and not spam bot. ";
echo "Use your back button and try again";
}

} else {
echo "You did not fill in all the fields. Please use your back button and fill in all required information";
}

exit();

?>

gkchicago

4:48 am on Jan 3, 2009 (gmt 0)

10+ Year Member



The message parameter for the mail function is simply treated as a string so for the sake of security you don't need to do any validation if you don't want to.

hostanything

5:44 am on Jan 3, 2009 (gmt 0)

10+ Year Member



Thanks, I googled, went to php.net, etc.. but I never could find any info on that ;)

eelixduppy

3:00 pm on Jan 3, 2009 (gmt 0)



Note that if any of the other fields were created by some data from the outside (eg from users) then that would have to be checked for email injections.

hostanything

4:04 pm on Jan 3, 2009 (gmt 0)

10+ Year Member



Thanks for the advice, validating the to, from, and subject is pretty simple, it's just if you have to validate all your form input, that becomes a pain in the %$$.