too long

I'm kinda new in PHP and I've created a form that should validate data and submit an error if any field is blank or incorrect. It doesn't tho. Even if email is wrong or any field is empty and the errors are shown it still sends an email. And the headers are not showing in the message. The only case when the errors are shown and the mail isn't send is the case when all fields are empty. Here's the code:

<?php
$NameErr = $EmailErr = $SubErr = $MessErr = "";
$Name = $Email = $Subject = $Message = "";
$header = "From: " . $Email . "Name: " . $Name . "
";
$header .= "Content-Type: text/plain";
$To = "xxx@gmail.com";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["Name"])) {
        $NameErr = "Name is required";
    } else {
        $Name = test_input($_POST["Name"]);
        if (!preg_match("/^[a-zA-Z ]*$/", $Name)) {
            $NameErr = "Only letters and white space allowed!";
        }
    }
    if (empty($_POST["Email"])) {
        $EmailErr = "Email is required";
    } else {
        $Email = test_input($_POST["Email"]);
        if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
            $EmailErr = "Invalid email format";
        }
    }
    if (empty($_POST["Subject"])) {
        $SubErr = "Subject is required";
    } else {
        $Subject = test_input($_POST["Subject"]);
    }
    if (empty($_POST["Message"])) {
        $MessErr = "Message is required";
    } else {
        $Message = test_input($_POST["Message"]);
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    <p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="Name"></p>
    <span class="error"> <?php echo $NameErr; ?></span>
    <p><input class="w3-input w3-padding-16" type="text" placeholder="Email" name="Email"></p>
    <span class="error"> <?php echo $EmailErr; ?></span>
    <p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="Subject"></p>
    <span class="error"> <?php echo $SubErr; ?></span>
    <p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="Message"></p>
    <span class="error"> <?php echo $MessErr; ?></span>
    <p>
        <button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit" value="Submit" name="pressed">
            <i class="fa fa-paper-plane"></i> SEND MESSAGE
        </button>
    </p>
</form>
<?php
if (isset($_POST["pressed"])) {
    if (empty($NameErr && $SubErr && $MessErr && $EmailErr)) {
        mail($To, $Subject, $Message, $header);
        echo "Email sent.";
    } else {
        echo "Error.";
    }
}
?> 

Can you help me? Error validating is on and it doesn't show me any errors.

use isset function instead of empty() to check if the field is posted or not. example:

if (!isset($_POST["Name"])) {
...

also there is no need to check the request method, $_POST will only catch post requests.

The way you're constructing your empty check towards the bottom is incorrect:

if (empty($NameErr && $SubErr && $MessErr && $EmailErr)){

The only way that this will evaluate to false is if all of the error messages are set, and the above snippet will break before PHP 5.5 (as Felippe mentioned in the comments). What you want instead is the below; it returns true only if none of the error messages are set:

if (empty($NameErr)
   && empty($SubErr)
   && empty($MessErr)
   && empty($EmailErr)) {

Another way to do this would be to

  • extract the validation logic into methods for readability,
  • read off of an $errors array instead of $NameErr, $SubjectErr, etc.
  • keep POST logic together (instead of split between the beginning and end)

To those ends, I've rewritten your snippet below:

<?php
function validateName($input)
{
    if (empty($input)) {
        return 'Name is required';
    }
    if (preg_match("/^[a-zA-Z ]*$/", $input) != 1) {
        return 'Name may only contain letters and spaces';
    }
    return null;
}

function validateEmail($input)
{
    if (empty($input)) {
        return 'Email is required';
    }
    if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
        return 'Email is in an invalid format';
    }
    return null;
}

function validateSubject($input)
{
    return empty($input) ? 'Subject is required' : null;
}

function validateMessage($input)
{
    return empty($input) ? 'Message is required' : null;
}

function test_input($data)
{
    return htmlspecialchars(stripslashes(trim($data)));
}

$errors = [];
$notification = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name = test_input($_POST['name'] ?: '');
    $email = test_input($_POST['email'] ?: '');
    $subject = test_input($_POST['subject'] ?: '');
    $message = test_input($_POST['message'] ?: '');

    if (($error = validateName($name)) !== null) {
        $errors['name'] = $error;
    }
    if (($error = validateEmail($email)) !== null) {
        $errors['email'] = $error;
    }
    if (($error = validateSubject($subject)) !== null) {
        $errors['subject'] = $error;
    }
    if (($error = validateMessage($message)) !== null) {
        $errors['message'] = $error;
    }

    if (empty($errors)) {
        $headers = [
            "From: $name <$email>",
            "Content-Type: text/plain",
        ];
        $to = "xxx@gmail.com";

        mail($to, $subject, $message, implode("
", $headers));
        $notification = 'The email was sent!';
    } else {
        $notification = 'The email could not be sent; please check below for errors.';
    }
}

?>
<form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
    <?php if (!empty($notification)): ?><p><?= $notification ?></p><?php endif; ?>

    <p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="name" required></p>
    <?php if (isset($errors['name'])): ?><span class="error"> <?= $errors['name'] ?></span><?php endif; ?>

    <p><input class="w3-input w3-padding-16" type="email" placeholder="Email" name="email" required></p>
    <?php if (isset($errors['email'])): ?><span class="error"> <?= $errors['email'] ?></span><?php endif; ?>

    <p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="subject" required></p>
    <?php if (isset($errors['subject'])): ?><span class="error"> <?= $errors['subject'] ?></span><?php endif; ?>

    <p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="message" required></p>
    <?php if (isset($errors['message'])): ?><span class="error"> <?= $errors['message'] ?></span><?php endif; ?>

    <p>
        <button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit">
            <i class="fa fa-paper-plane"></i> SEND MESSAGE
        </button>
    </p>
</form>

So I've re designed the code structure for you. Generally calling a class and a function will keep your files and your code cleaner.

So with this being said, let me show you some insight. This is where your form will be located for example: form.php

<?php

require ('mail.php');

$send = new Mail();

if (isset($_POST['sendIt']))
{
    $send->sendMail($_POST['nameP'], $_POST['email'], $_POST['subject'], $_POST['message']); // Call the class and function
}

?>


<form id="contact" method="post">
    <div class="container">
        <input type="text" name="nameP" placeholder="Name *" /><br />
        <input  type="email" name="email" placeholder="Email *"/><br />
        <input type="text" name="subject" placeholder="Subject *"><br />
        <textarea name="message" id="" cols="30" rows="10"></textarea>
        <input type="submit" name="sendIt" id="submit">
    </div>
</form>

Then create yourself a mail.php file to store the class and the functions revolving around mailing in general:

<?php

class Mail
{
    public function sendMail($name, $email, $subject, $message)
    {
        if (!empty($name))
        {
            if (!empty($email))
            {
                if (!empty($subject))
                {
                    if (!empty($message))
                    {
                                $email_to = 'Your@emailAddress';
                                $header = 'From: ' . $name ."<noreply@youremail>". "
" .
                                    'Reply-To: ' . $email . "
" .
                                    'X-Mailer: PHP/' . phpversion();

                                @mail($email_to, 'Enquiry Received', 'Name: ' . $name . "

". 'Email Address: ' .$email."

" . 'Message: ' .$message."

". $header);

                                echo "SUCCESS MESSAGE";
                    } else {
                        echo "Please fill in your message";
                    }
                } else {
                    echo "Please provide a subject.";
                }
            } else {
                echo "Please provide your email address.";
            }
        } else {
            echo "Please provide your name.";
        }

    }
}
?>

This will generally clear the form if there is an error by default however you can then simply add value="<?php echo $_POST['whateverThisFormIsFor'];?>

I hope this will help and give you some further insight.