George Hoyt
George Hoyt

Reputation: 1

How do I fix this php email submit form?


I am new to PHP, how would one change this code so that this php mail file checks that the form data is actually there?

My goal here is to prevent bots and malicious users from sending blank emails by simply accessing the php mail in the browser.

Regards,
George

<?php

$to_email = '[email protected]';
$subject = 'Service Request';
$Body_Msg = "A new contact form submitted by ".$_REQUEST["F_Name"].
            " \r\n Name: ". $_REQUEST["F_Name"].
            "\r\nPhone No: ".$_REQUEST["your_phone"].
           " \r\nEmail: ".$_REQUEST["email_id"].
           "\r\nServices wanted: ".$_REQUEST["services"].
           "\r\nAddress: ".$_REQUEST["Address"].
           "\r\nMessage: ".$_REQUEST["Message"].
nl2br($Body_Msg);
$headers = 'From: [email protected]';
mail($to_email,$subject,$Body_Msg,$headers);
echo "Thank you for contacting My Company. We will revert you shortly.";


?>

<script type="text/javascript">
    window.setTimeout(function(){

        // Move to a new location or you can do something else
        window.location.href = "contact.html";

    }, 500);
</script>

Upvotes: 0

Views: 48

Answers (2)

Progrock
Progrock

Reputation: 7485

Here is some code that checks that a form attribute email is passed over HTTP POST, and if so assigns to a variable.

<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
    if(isset($_POST['email'])) {
        $email = $_POST['email'];
    }
    if(is_null($email)) {
        die('No email field posted.');
    }
}

Note: an empty string passed will not terminate with the 'No email field posted.' message.

You can reduce the if - isset and assignment above to the equivalent:

 $email = $_POST['email'] ?? null;

You'll likely further need to validate and/or filter/sanitize your data, to prevent user input exploits (i.e. email header injection - that can lead to form/email spamming).

Upvotes: 0

Shir Gans
Shir Gans

Reputation: 2027

There are many many factors to apply when securing forms. Better to go ahead and follow a good guide (out of many out there). https://wp-mix.com/php-securing-email-scripts/

This will tighten your security. Also, it's always a good practice to add captcha to your html form.

Good luck

Upvotes: 1

Related Questions