'PHP mail sending empty mails

I'm similar to php and don't undestand what is the problem.

Sometimes php function send me empty messages like

Vanema nimi
Lapse nimi:
Linn:
Telefoninumber:
Email:
Sünnikuupäev:
Sõnumi tekst:

But it should be filled with values like this

Vanema nimi test
Lapse nimi: test
Linn: test
Telefoninumber: test
Email: test@test
Sünnikuupäev: 21313
Sõnumi tekst:test

Here is my php code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Обратная Связь</title>
  </head>
  <body>
    <?php
      if (isset($_POST['parent'])) {$parent = $_POST['parent'];}
      if (isset($_POST['child'])) {$child = $_POST['child'];}
      if (isset($_POST['contacts'])) {$contacts = $_POST['contacts'];}
      if (isset($_POST['email'])) {$email = $_POST['email'];}
      if (isset($_POST['bbd'])) {$bbd = $_POST['bbd'];}
      if (isset($_POST['city'])) {$city = $_POST['city'];}
      if (isset($_POST['mess'])) {$mess = $_POST['mess'];}
 
      $to = "[email protected]"; /*Укажите ваш адрес электоронной почты*/
      $headers = "Content-type: text/plain; text/html; charset=utf-8";
      $subject = "Kontakti Info";
      $message = "Vanema nimi $parent \n Lapse nimi: $child \nLinn: 
      $city \nTelefoninumber: $contacts \nEmail: $email \nSünnikuupäev: $bbd \nSõnumi tekst: $mess";
      $send = mail ($to, $subject, $message, $headers);
      if ($send == 'true')
        {
        echo "<b>Спасибо за отправку вашего сообщения!<p>";
        echo "<a href=index.php>Нажмите,</a> чтобы вернуться на главную страницу";
        }
      else 
        {
        echo "<p><b>Ошибка. Сообщение не отправлено!";
        } 
    ?>
  </body>
</html>

<?php
  header('Location: https://test.ee/aitah.html ');
?>

Please give me advice what is wrong.



Solution 1:[1]

If your script is a form processor only, you could e.g. add if(empty($_POST)) { die('No form data!'); } to the top to prevent it from running, except in response to a form submission.

If you require all fields to be filled in, you will have to check each of them before you process your email. You could cram all of those issets into one monster if(isset(...) statement. However, there's a simpler and more readable way to do it. First, let's set up a couple of variables:

// Your required fields:
$fields = ['parent', 'child', 'contacts', 'email', 'bbd', 'city', 'mess'];
// Your data is collected here:
$data = [];
// Any errors are collected here:
$errors = [];

Then, we loop over the fields and if values exist, add to $data, otherwise we add an error note.

// Loop to check your required fields:

foreach($fields as $field) {
    // If value exists, add to $data:
    if(!empty($_POST[$field])) {
        $data[$field] = $_POST[$field];
    }
    // Else add error:
    else {
        $errors[] = 'Missing field: ' . $field;
    }
}

if(empty($errors)) {
    // No errors, send your email
    // You can use "Vanema nimi {$data['parent']}...",
    // ... otherwise: extract($data) to use $parent etc.
}
else {
    // You could report those errors, or redirect back to the form, or whatever.
}

If there are errors (= missing fields), e-mails won't be sent. As a bonus, you now have a reusable piece of code that you can use for other forms with similar functionality simply by modifying the $fields array. (Wrapping it into a function is a good idea if you do need to reuse it; don't copy-paste code. function x($post, $fields) { ... } for a basic helper function.)

Note that here we are using empty in place of isset. If a blank form is submitted, the fields are set (to empty strings ""). Also note that empty returns true for anything that equals false (ie. "", 0, false, null, []). (If "0" is an expected and acceptable value, be aware of its "emptiness"!) On the other hand, isset returns true for anything not null.

P.S. If your code above is the complete code, and your script simply processes the form data and redirects, then you don't really need the HTML wrapper at all. It will never be displayed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1