GiedraitytÄ— Greta GiedraitytÄ— Greta - 1 month ago 19
CSS Question

Html email form PHP

i have a html form that works with php code, and i get the emails sent to me, however, i can get an email if there is no subject, no email and no message. Maybe some one know how to fix that? Here's the php code:

<?php
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_message = $_POST['cf_message'];

$mail_to = 'benasleng@gmail.com';
$subject = 'Message from a site visitor '.$field_name;

$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;

$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message. We will contact you shortly.');
window.location = 'index.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, send an email to benasleng@gmail.com');
window.location = 'index.html';
</script>
<?php
}
?>
<?php
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);

$inject = join('|', $injections);
$inject = "/$inject/i";

if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}

if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
?>

Answer

before calling mail() function, you should check if fields are compiled .

This is just a draft example because i suggest you to use more complex checks than just empty() function, expecially on $field_email, for example:

if (empty($field_name) || !filter_var($field_email, FILTER_VALIDATE_EMAIL) || empty($field_message)) {
  ?>
    <script language="javascript" type="text/javascript">
        alert('All fields must be correctly compiled');
        window.location = 'index.html';
    </script>
<?php

} else {


$mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) { ?>
    <script language="javascript" type="text/javascript">
        alert('Thank you for the message. We will contact you shortly.');
        window.location = 'index.html';
    </script>
<?php
}
else { ?>
    <script language="javascript" type="text/javascript">
        alert('Message failed. Please, send an email to benasleng@gmail.com');
        window.location = 'index.html';
    </script>
<?php
}
}
Comments