联系表格名称字符串

时间:2016-07-31 10:21:14

标签: php forms

我试图这样做,当用户发送表格时,主题行显示用户的名字,如#34;来自[用户名称]"的查询。它现在如何设置主题"来自网站的联系表格。"如何修改代码以实现这一目标?

<?php
// configure
$from = 'info@mysite.com'; 
$sendTo = 'info@mysite.com';
$subject = 'Contact form at site';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Your Message was successfully submitted. Thank you! We will get back to you soon.';
$errorMessage = 'There was an error while submitting the form. Please try again or call us at 970-201-9619';

// let's do the sending

try
{
    $emailText = "You have new message from your Website\n=============================\n";

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

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

    mail($sendTo, $subject, $emailText, "From: " . $from);

    $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'];
}

1 个答案:

答案 0 :(得分:0)

根据您的要求对主题进行更改。我已将主题变量移到邮件发送代码的正上方,并将用户的姓名与主题行连接起来。请查看下面的代码段,如果您有任何疑问,请与我们联系。

<?php
// configure
$from = 'info@mysite.com'; 
$sendTo = 'info@mysite.com';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Your Message was successfully submitted. Thank you! We will get back to you soon.';
$errorMessage = 'There was an error while submitting the form. Please try again or call us at 970-201-9619';

// let's do the sending

try
{
    $emailText = "You have new message from your Website\n=============================\n";

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

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }
    $subject = 'Inquiry from '.$_POST['name']." ".$_POST['surname'];
    mail($sendTo, $subject, $emailText, "From: " . $from);

    $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'];
}
?>