PHP form: Success email with only filled fields

2019-09-02 13:51发布

问题:

Been struggling with this for some time now. Basically I have 6 fields, name, email, phone, location, date and budget. Name and email are the only required fields. When I get the email I see rest of the fields as well. Is it possible to receive only fields that have been filled?

Here's the code;

<?php
// get posted data into local variables
$EmailFrom = "email@email.com";
$EmailTo = "email@email.com";
$Subject = "My form";
$Name = Trim(stripslashes($_POST['Name'])); 
$Email = Trim(stripslashes($_POST['Email'])); 
$Phone = Trim(stripslashes($_POST['Phone']));

$Location = Trim(stripslashes($_POST['Location'])); 
$Date = Trim(stripslashes($_POST['Date']));
$Budget = Trim(stripslashes($_POST['Budget'])); 

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=#\">";
  exit;
}

$userip = ($_SERVER['X_FORWARDED_FOR']) ? $_SERVER['X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];

// prepare email body text
$Body = "";
$Body .= "Location: "; $Body .= $Location; $Body .= "\n";
$Body .= "Date: "; $Body .= $Date; $Body .= "\n";
$Body .= "Budget: "; $Body .= $Budget; $Body .= "\n";

$Body .= "Name: "; $Body .= $Name; $Body .= "\n";
$Body .= "Email: "; $Body .= $Email; $Body .= "\n";
$Body .= "Phone: "; $Body .= $Phone; $Body .= "\n";
$Body .= "User's IP: ". $userip;

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=#\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=#\">";
}
?>

回答1:

Use empty to check if a value was posted or not:

$Phone = !empty($_POST['Phone']) ? trim(stripslashes($_POST['Phone'])) : false;

Then later $Phone will be false if it wasn't filled in and you can do this:

if($Phone)
    $Body .= "Phone: "; $Body .= $Phone; $Body .= "\n";


回答2:

You can simply do a check to see if the value is there. you could do this:

if (!empty($Location) { $Body .= "Location: "; $Body .= $Location; $Body .= "\n"; }

ect ect. This is saying if location is not empty then do that code



回答3:

Yes it is, just add a check before you concat the fields to the body like:

if(!$Location)
{
    $Body .= "Location: "; $Body .= $Location; $Body .= "\n";
}
/*You can also use empty like: */
if(!empty($Date))
{
    $Body .= "Location: "; $Body .= $Date; $Body .= "\n";
}
/*Continue here*/


回答4:

if (isset($_POST['phone'] && !empty($_POST['phone']){
    $phone = $_POST['phone'];
    //add $phone to email body
}


标签: php forms