3

PHP: Do not Email Form Fields Left in White

 2 years ago
source link: https://www.codesd.com/item/php-do-not-email-form-fields-left-in-white.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PHP: Do not Email Form Fields Left in White

advertisements

Currently I am making an online enquiry form with a set of fields that are non-mandatory.

If a non-mandatory form field is not filled-in out, I would like to make it so that it doesn't come through in the processed email.

For instance; if someone does not enter their telephone number, the "Telephone: $atelephone" component does not come through.

if ($atelephone != '') {
echo "Telephone: ".$atelephone;
}

I figure the code should have something like above put in it, though I am struggling to connect the dots. Any help would be greatly appreciated. (I hope this makes sense).

<?php 

// Base form items

$asender = $HTTP_POST_VARS['name'] ." <". $HTTP_POST_VARS['email'] .">";
$asubject = "Email Enquiry: ".$HTTP_POST_VARS['subject'];
$arecipient = "[email protected]";

/*******************************************************/
// Mail form variables //

$aname = $HTTP_POST_VARS['name'];
$aemail = $HTTP_POST_VARS['email'];
$atelephone = $HTTP_POST_VARS['telephone'];
$asuburb = $HTTP_POST_VARS['suburb'];
$aenquiry = $HTTP_POST_VARS['enquiry'];

mail("$arecipient","$asubject",
"
===========================================
Please note: this is an email
generated from the Website.
=========================================== 

Name: $aname
Email: $aemail
Telephone: $atelephone
Suburb: $asuburb

Message:
$aenquiry 

================================ ","FROM:$asender"); 

header('Location: /thank-you.php');

?>


You're on the right track. The last step is make a string to input in your final message:

$_POST['telephone'] ?
  $telephoneString = "Telephone: ".$_POST['telephone'] ."\n" :
  $telephoneString = "";

(The \n at the end of the string makes a newline.)

Then, output the string in the message. It will be empty, or not.

  "foo bar baz
  ===========================================".
  $nameString.
  $emailString.
  $telephoneString.
  $suburbString;

Edit

This may work better for individual form fields. However, for elegance, I prefer the solution from @mazzzzzz.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK