Отправка формы с внутренних (2-го уровня) страниц - PullRequest
0 голосов
/ 01 июля 2019

У меня есть контактная форма в нижнем колонтитуле моего сайта, которая использует PHPMailer ... поэтому он отображается на всех страницах как часть шаблона. Он отлично работает на страницах «верхнего» уровня, т.е. www.mywebsite.com/index.html, но на внутренних страницах (или страницах 2-го уровня, т.е. www.mywebsite.com/pricing/basic.html) не отправляется. Консоль говорит, что не может найти файл "contact.php", который находится в корне каталога моего сайта.

Я пытался добавить "../contact.php" в качестве действия формы, чтобы подняться на уровень, но он все еще не находит его.

<?php

/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
*/

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer-master/vendor/autoload.php';

/*
*  CONFIGURE EVERYTHING HERE
*/

// an email address that will be in the From field of the email.
$fromEmail = 'xxxxxxxx';
$fromName = 'No Reply Email';

// an email address that will receive the email with the output of the form
$sendToEmail = 'xxxxxx';
$sendToName = 'New Contact Form Message';

// 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:', 'email' => 'Email:', 'message' => 'Message:');

// message that will be displayed when everything is OK :)
$okMessage = 'Successfully submitted - we 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);
error_reporting(E_ALL & ~E_NOTICE);

try {

    if (count($_POST) == 0) throw new \Exception('Form is empty');
    $emailTextHtml .= "<h3>New message from xxxxx xxxxx:</h3><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>";
    $emailTextHtml .= "<p>Have a great day!<br><br>Sincerely,<br><br>xxxx xxxx</p>";

    $mail = new PHPMailer;

    $mail->setFrom($fromEmail, $fromName);
    $mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
    $mail->addReplyTo($_POST['email'], $_POST['name']);



    $mail->Subject = $subject;

    $mail->Body = $emailTextHtml;
    $mail->isHTML(true);
    //$mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy


    if (!$mail->send()) {
        throw new \Exception('Email send failed. ' . $mail->ErrorInfo);
    }

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


// if requested by AJAX request return JSON response
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 just display the message
else {
    echo $responseArray['message'];
}

1 Ответ

0 голосов
/ 01 июля 2019

Похоже, это не имеет ничего общего с тем, что в этом скрипте, а с тем, откуда оно загружено. Попробуйте указать действие формы для абсолютного пути, а не относительного, т.е. action="/contact.php", а не относительного action="contact.php" или action="../contact.php". Таким образом, он всегда будет указывать на один и тот же скрипт, независимо от того, откуда он был отправлен.

Отдельно от проблемы, которую вы описываете, эта строка выглядит подозрительно:

require 'PHPMailer-master/vendor/autoload.php';

Это говорит о том, что вы можете использовать собственный файл composer.json PHPMailer; Вы должны использовать это, только если вы работаете на PHPMailer, а не просто используете его в своем проекте. Обычно вы ожидаете, что папка vendor и файл composer.json будут на верхнем уровне вашего собственного проекта, а файлы PHPMailer были бы помещены в vendor/phpmailer композитором - хотя вам не нужно об этом беспокоиться, потому что vendor/autoload.php выяснит это. Пожалуйста, прочтите readme, чтобы узнать, как установить PHPMailer в ваш собственный проект, используя composer.

...