简体   繁体   中英

PHP mail script not working after removing html tags in htaccess

Currently, I'm running a php script, with js validator & success message pop-up, which currently works fine.

I've recently been experimenting with an update to the website, removing the html tags via the htaccess file so the URL looks better in the address bar. The whole site works great, with the new links etc. which all display fine. However, the php email script and js validator now don't work, and the emails are no longer generating. The relevant code is here:

HTML (the page title is contact-us.html):

<form id="contact-form" method="post" action="http://www.mywebsite.co.uk/contact.php" role="form">
                        <div class="messages"></div>
                        <div class="controls">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label for="form_name">Name *</label>
                                        <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Please enter your name">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                </div>
                                <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label for="form_email">Email *</label>
                                        <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="Please enter a valid email address.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                </div>
                                <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label for="form_phone">Telephone</label>
                                        <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your telephone number">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label for="form_message">Message *</label>
                                        <textarea id="form_message" name="message" class="form-control" placeholder="Your mssage *" rows="4" required="required" data-error="Please enter your message"></textarea>
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>

                                <div class="col-md-12">
                                    <div class="form-group">
                                        <!-- Replace data-sitekey with your own one, generated at https://www.google.com/recaptcha/admin -->
                                        <div class="g-recaptcha" data-sitekey="XXXXXXXX"></div>
                                    </div>
                                </div>

                                <div class="col-md-12">
                                    <input type="submit" class="btn btn-success btn-send" value="Send message">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12"><br>
                                    <p class="text-muted"><strong>*</strong> These fields are required.</p>
                                </div>
                            </div>
                        </div>

                    </form>

Contact.php is as follows:

<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');

// configure
$from = 'contact@mywebsite.co.uk';
$sendTo = 'me@mywebsite.co.uk';
$subject = 'New message mywebsite.co.uk';
$fields = array('name' => 'Name', 'phone' => 'Phone', 'e
' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in the email
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please reload the page and try again.';
$recaptchaSecret = 'SECRETKEYXXX';

   {
    if (!empty($_POST)) {

        // validate the ReCaptcha, if something is wrong, we throw an Exception,
        // i.e. code stops executing and goes to catch() block

        if (!isset($_POST['g-recaptcha-response'])) {
            throw new \Exception('ReCaptcha is not set.');
        }


        $recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());


        $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);


        if (!$response->isSuccess()) {
            throw new \Exception('ReCaptcha was not validated.');
        }

        $emailText = "You have a new message from MyWebsite.co.uk\n============================= \n";

        foreach ($_POST as $key => $value) {

            if (isset($fields[$key])) {
                $emailText .= "$fields[$key]: $value\n";
            }
        }


        $headers = array('Content-Type: text/plain; charset="UTF-8";',
            'From: ' . $from,
            'Reply-To: ' . $from,
            'Return-Path: ' . $from,
        );

        mail($sendTo, $subject, $emailText, implode("\n", $headers));

        $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}

Contact.js (which is linked to after the footer of contact-us.html code):

$(function () {

    $('#contact-form').validator();

    $('#contact-form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    if (messageAlert && messageText) {
                        $('#contact-form').find('.messages').html(alertBox);
                        $('#contact-form')[0].reset();
                        grecaptcha.reset();
                    }
                }
            });
            return false;
        }
    })
});

And finally, the part of htaccess shortening the URLs:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Because you are changing .php extension to .html you need to change your form:

<form id="contact-form" method="post" action="http://www.mywebsite.co.uk/contact.html" role="form">

var url = "contact.html";

The normal way would be to remove extensions and create "pretty urls", then you would do:

<form id="contact-form" method="post" action="http://www.mywebsite.co.uk/contact" role="form">

var url = "/contact";

I really suggest creating pretty URLs .

Instead of sending header array make it string as // Set content-type header for sending HTML email

$headers= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: your name<my@domain.com>' . "\r\n";
$headers .= 'Return-Path: mail@testsite.com' . "\r\n";
$headers .= 'reply-to: your name<my@domain.com>' . "\r\n";
$headers .= "Cc: another name < name@domain.com >\n"; 

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