Question

I have a simple php mail script which has a client-side verification (jquery based), works fine. But some times someone make a direct post to it and I've reseive many empty spam emails.

How I can check, if some field is not null (empty). For example, "usermail" variable.

<?php
$sendto   = "youremail@youremail.com";
$usermail = $_POST['email'];
$content  = nl2br($_POST['msg']);

$subject  = "New Feedback Message";
$headers  = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";

$msg  = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";


if(@mail($sendto, $subject, $msg, $headers)) {
    echo "true";
} else {
    echo "false";
}

?>

This is not working:

<?php
if(!empty($usermail)) {
$sendto   = "mymail@mail.com";
$usermail = $_POST['email'];
$content  = nl2br($_POST['msg']);

$subject  = "New Feedback Message";
$headers  = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";

$msg  = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";


if(@mail($sendto, $subject, $msg, $headers)) {
        echo "true";
} else {
        echo "false";
}
}
?>
Was it helpful?

Solution

Well, you can use function empty()

if (empty($_POST['email']) || empty($_POST['msg'])) {
    exit();
}

The better way is to have a proper email validation and message validation. For example:

  • Message must be longer than certain length (for example: must be greater than 10 characters)
  • Must provide a valid format email (for example: the simplest way and less accurate way to check is to check if @ exists.

OTHER TIPS

Use !empty($usermail) or $usermail !== '';. You should also make sure the page is $_POST['submitName'] as well.

You can use the following syntax to check the value of variable.

if ($a==null)
{
  exit(0)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top