HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Is this a secure and best-practice PHP mail() function?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thissecurepracticephpfunctionmailandbest

Problem

Is the following PHP laid out fine to go inside the mail function?

$to = "My Name ";
$subject = "Contact Form: $name";
$message = "Name: $name\r\nEmail: $email\r\nMessage:\r\n$message";
$headers = "From: Contact Form ";

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


Should there be any spaces around the \r\n? Any important headers to include?

Any tips on how to improve it are welcome.

If you're interested, please the full script below. It is adapted from here — it's allegedly secure... is it?

```
$value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);

$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

// Test input values for errors
$errors = array();
if(strlen($name) ".$error."";
}
die("The following errors occured:". $errortext ."");
}

// Send the email
$to = "YOUR_EMAIL";
$subject = "Contact Form: $name";
$message = "$message";
$headers = "From: $email";

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

// Die with a success message
die("Success! Your message has been sent.");

// A function that checks to see if
// an email is valid
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $loc

Solution

As far as I think, your script is good and will achieve the required task. But before finalising on this script, you should read about PHPMAILER. It is easy to implement and will provide you many features like to add CC, BCC, and attachments. The mail() function is the easiest way, but as far as I think, it is a bit limited. Also, PHPMailer is easily available on the Internet.

Context

StackExchange Code Review Q#19365, answer score: 4

Revisions (0)

No revisions yet.