字段值不会使用 PHP 在电子邮件中发送


Field values are not sent in the email using PHP

邮件已发送,但表单域的值未发送。

我正在使用以下代码。

<?php
header('Content-type: application/json');
$status = array(
    'type'=>'success',
    'message'=>'Thank you for contact us. As early as possible  we will   contact you '
);
$name = @trim(stripslashes($_POST['name'])); 
$email = @trim(stripslashes($_POST['email'])); 
$subject = @trim(stripslashes($_POST['subject'])); 
$message = @trim(stripslashes($_POST['message'])); 
$email_from = $email;
$email_to = 'some@email.com';//replace with your email
$body = 'Name: ' . $name . "'n'n" . 'Email: ' . $email . "'n'n" . 'Subject: ' . $subject . "'n'n" . 'Message: ' . $message;
$success = @mail($email_to, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>

您的代码流不正确。您的$status无需进行任何验证即可成功。此外,我们的问题中缺少HTML表单,这就是它不起作用的原因。

<?php
  header('Content-type: application/json');
  if(
      isset($_POST['name']) &&
      isset($_POST['email']) &&
      isset($_POST['subject']) &&
      isset($_POST['message']))
  {
    # Here you should do some actual validation..
    #  1. is email address valid?
    if(!filter_var($email, FILTER_VALIDATE_EMAIL) === false){
      # The email has a correct format
      // etc, etc, etc.
    } else {
      $status = [
      'type' => 'failed',
      'message' => 'Incorrect email address'
      ];
    }
  } else {
    $status = [
    'type' => 'failed',
    'message' => 'Missing fields: ' . var_export($_POST) . ' But wait a minute...: ' . var_export($_GET)
    ];
  }
  die(json_encode($status));
?>

对于 HTML:

<form method="post" action="yourphpfile.php">
  <input type="text" name="name" value="">
  <input type="text" name="email" value="">
  <input type="text" name="subject" value="">
  <input type="text" name="message" value="">
  <input type="submit" value="Submit">
</form>

为什么要使用 @ 来禁止显示错误消息?

  1. 错误消息对于调试代码很有用。(但你压制他们并寻求帮助)
  2. 使用它们是PHP编程中的不良做法。
  3. trim功能之前无用,它总是期望工作。