Question: I've been looking around for ages and haven't found an easy way of editing this code so that when the user hasn't typed anything into a required field (all of the fields are required) an alert is shown asking the user to please enter something.

Can anyone help?

```
<?php
    $field_name = $_POST['name'];
    $field_email = $_POST['email'];
    $field_message = $_POST['message'];

    $mail_to = 'you@yourdomain.com';
    $subject = 'Site Mail';

    $body_message = 'From: '.$field_name."\n";
    $body_message .= 'Email: '.$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('Thanks! Your email has been sent.');
            window.location = 'index.html';
        </script>
    <?php
    }
    else { ?>
        <script language="javascript" type="text/javascript">
            alert('Sorry, something went wrong.');
            window.location = 'index.html';
        </script>
    <?php
    }
?>

```

Answer: 
You can use [**required**](https://www.google.com.ph/search?q=html5%20required&oq=html5%20re&aqs=chrome.4.69i57j69i60l2j0l3.3450j0&sourceid=chrome&ie=UTF-8#bav=on.2,or.r_qf.&fp=a91aea830d00bed6&q=html5%20required%20input) attribute if you want to take advantage of `html5` features.

Try this **[LINK](http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_required)**. It shows a simple demo of how to use the `required` attribute.
**[This](http://www.wufoo.com/html5/attributes/09-required.html)** one too
The most common way to check for required fields is both on the client side (to inform the user) and the server side (to check the data is legit before we send it).

On the client side, at the point at which the form is submitted we should check to see if the fields are correct and ask the user to fix mistakes. There are a bunch of great helper libraries available to do this, a couple of the more common libraries are <http://parsleyjs.org/> and <http://jqueryvalidation.org/> both use jQuery and have easy examples to get started.

On the server side, as some commenters have noted, your current script is vulnerable to header injection and other nasty stuff. You might want to switch to using a library such as swiftmailer which will prevent a lot of bad stuff happening. Here is a really simple example of how to send email <http://swiftmailer.org/docs/sending.html> 

To add server side validation to you example, as simple approach would be to check the values of `$_POST['name'];` before calling `$mailer->send($message);`