Форма PHPMailer не выдает ошибок и не отправляет - PullRequest
1 голос
/ 02 августа 2020

Отсутствие ошибок в error_log или на странице. Журнал ошибок определенно работает так, как будто я меняю require 'PHPMailer.php'; на require 'PHPFailer.php'; Я получаю PHP Fatal error: require(): Failed

display_errors, установленного на true

error_reporting установлен на E_ALL & ~E_NOTICE

PHPMailer 6.1 .7 - PHP 7.2

И PHPMailer. php, и Exception. php находятся в каталоге root. Закомментировали перенаправления, так как меня просто отправили на /php/form_error.php.

Любые идеи были бы очень признательны, спасибо.

contact_post. php

<?php
    /*
    THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
    */
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
    require 'PHPMailer.php';
    require 'Exception.php';
    
    /*
    *  CONFIGURE EVERYTHING HERE
    */
    
    // an email address that will be in the From field of the email.
    $fromEmail = 'info@domain.co.uk';
    $fromName = 'Info domain';
    
    // an email address that will receive the email with the output of the form
    $sendToEmail = 'info@domain.co.uk';
    $sendToName = 'Info domain';
    
    // subject of the email
    $subject = 'New message from contact form';
    
    // form field names and their translations.
    // array variable name => Text to appear in the email
    $fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
    
    // message that will be displayed when everything is OK :)
    $okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
    
    // If something goes wrong, we will display this message.
    $errorMessage = 'There was an error while submitting the form. Please try again later';
    
    /*
     *  LET'S DO THE SENDING
     */
    
    // if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    
    try
    {
        
        if(count($_POST) == 0) throw new \Exception('Form is empty');
        $emailTextHtml = "<h1>You have a new message from your contact form</h1><hr>";
        $emailTextHtml .= "<table>";
        
        foreach ($_POST as $key => $value) {
            // If the field exists in the $fields array, include it in the email
            if (isset($fields[$key])) {
                $emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
            }
        }
        $emailTextHtml .= "</table><hr>";
        
        $mail = new PHPMailer(true);
        
        $mail->setFrom($fromEmail, $fromName);
        $mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
        $mail->addReplyTo($from);
    
        $mail->isHTML(true);
        
        $mail->Subject = $subject;
        $mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy
        
        if(!$mail->send()) {
            throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
        }
        
        $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
    catch (\Exception $e)
    {
        // $responseArray = array('type' => 'danger', 'message' => $errorMessage);
        $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
    }
    
    
    // if requested by AJAX request return JSON response
    if ($responseArray['type'] == 'success') {
        // success redirect
    
       //header('Location: /php/form_complete.php');
    }
    else {
        //error redirect
        //header('Location: /php/form_error.php');
    }

форма при контакте. html

<form id="contact-form" method="post" action="/contact_post.php" role="form">

    <div class="messages"></div>

    <div class="controls">

        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_name">First name*</label>
                    <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your first name *" required="required" data-error="First name is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_lastname">Last name*</label>
                    <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your last name *" required="required" data-error="Last name is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <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 *" required="required" data-error="Valid email is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_need">Please specify your need*</label>
                    <select id="form_need" name="need" class="form-control" required="required" data-error="Please specify your need.">
                        <option value=""></option>
                        <option value="Request quotation">Request quotation</option>
                        <option value="Request order status">Request order status</option>
                        <option value="Request copy of an invoice">Request copy of an invoice</option>
                        <option value="Other">Other</option>
                    </select>
                    <div class="help-block with-errors"></div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="form_message">Message*</label>
                    <textarea id="form_message" name="message" class="form-control" placeholder="Please enter message here*" rows="4" required="required" data-error="Please, leave us a message."></textarea>
                    <div class="help-block with-errors"></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">
                <p class="text-muted">
                    <strong>*</strong> These fields are required.
                </p>
            </div>
        </div>
    </div>

</form>

файл htaccess

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^(.+)\.php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,END]
Options -Indexes

1 Ответ

1 голос
/ 03 августа 2020

В дополнение к моему комментарию, вы ничего не делаете, когда что-то идет не так, поэтому нечего видеть.

Чтобы увидеть, что на самом деле идет не так, выведите что-нибудь полезное, когда это произойдет, например:

catch (\Exception $e)
{
    $responseArray = ['type' => 'danger', 'message' => $e->getMessage()];
    var_dump($responseArray, $mail->ErrorInfo);
}

Одна мелочь:

    if(!$mail->send()) {
        throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
    }

В этом нет необходимости - PHPMailer уже настроен на выдачу исключений, поэтому это должно быть просто:

$mail->send();
...