简体   繁体   中英

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 = 'myemail@myemail.com';
$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: website@mywebsite.com';
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>

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

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 (ie email header injection - that can lead to form/email spamming).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM