php - 我怎样才能让这个表格中的姓名、电子邮件和主题成为我从服务器收到的消息中的实际值?
问题描述
如何在顶部配置变量 $from 和 $subject 以便服务器发送给我的电子邮件使用这些值而不是静态文本?
<?php
// configure
$from = 'Demo contact form <demo@domain.com>';
$sendTo = 'Demo contact form <demo@domain.com>'; // Add Your Email
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'subject' => 'Subject', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in the email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from contact form\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'];
}
我希望 $from 使用 Name 值和 $subject 使用 Subject 值。
解决方案
使用以下内容:
# checks if the 'name' key has been $_POST'ed
$from = isset($_POST['name'])?$_POST['name']:$from;
# checks if the 'subject' key has been $_POST'ed
$subject = isset($_POST['subject'])?$_POST['subject']:$subject;
推荐阅读
- ios - 滚动视图中的 GestureRecognizer 不起作用
- detection - Aframe 陀螺仪检测
- java - 如何在spring boot中使用spring web services动态WSDL生成?
- sql - SQL 连接字符串,然后删除空格
- android - 如何创建从我的应用到 Facebook 页面的意图?
- r - 在具有多个参数的用户定义函数上使用 apply/sapply
- python - 如何在 Azure 数据工厂中使用 Azure 函数 (Python) 作为 HTTP 数据集
- c++ - 多次调用 ruby_init 和 ruby_finalize
- vue.js - vue-cli npm 安装问题
- asp.net-core - 为什么在 ASP.NET Core WebAPI 项目中使用 OAuth2 时出现“未指定身份验证方案”错误?