Link to home
Start Free TrialLog in
Avatar of Nicholas_BlueStar
Nicholas_BlueStar

asked on

HTML + PHP form issues

I am having an issue with creating a form on my website that will automatically send me an email with the info filled out in the form.

Here is my code. Can someone look at it and let me know what is wrong?





PHP CODE:

<?php

if(!$_POST) exit;

$email = $_POST['email'];


//$error[] = preg_match('/\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $_POST['email']) ? '' : 'INVALID EMAIL ADDRESS';
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."@"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email )){
      $error.="Invalid email address entered";
      $errors=1;
}
if($errors==1) echo $error;
else{
      $values = array ('name','email','message');
      $required = array('name','email','message');
      
      $your_email = "james@example.com";
      $email_subject = "New Message: ".$_POST['subject'];
      $email_content = "new message:\n";
      
      foreach($values as $key => $value){
        if(in_array($value,$required)){
            if ($key != 'subject' && $key != 'company') {
              if( empty($_POST[$value]) ) { echo 'PLEASE FILL IN REQUIRED FIELDS'; exit; }
            }
            $email_content .= $value.': '.$_POST[$value]."\n";
        }
      }
      
      if(@mail($your_email,$email_subject,$email_content)) {
            echo 'Message sent!';
      } else {
            echo 'ERROR!';
      }
}
?>



I deleted line # 13 "if($errors==1) echo $error;" - and it sent one test email to an @me.com account. I then changed the email it should be sent to, to the correct address @companydomain.com and I am now getting an "ERROR!" when I hit submit.

Can anyone steer me in the right direction?
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Then your mail() functions is returning an error.  The '@' suppresses the reporting of an error but it does not make not be an error.  Unfortunately, the PHP mail function does not return any error messages to help you fix the problem.  And even when the function call succeeds, it does not mean the email was even sent, just that the function completed.

You are also not including the headers that are required now by most mail servers.  Here is my PHP email demo.  Save it as 'Email.php' so it can POST to itself and change the $toText to your email address.
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');

# some settings of POST vars
if (!isset($_POST['submit']))  $submit = ''; else $submit = $_POST['submit'];
if (!isset($_POST['subjectText'])) $subjectText = ''; else $subjectText = $_POST['subjectText'];
if (!isset($_POST['msgText'])) $msgText = ''; else $msgText = $_POST['msgText'];
if (!isset($_POST['ccText'])) $ccText = ''; else $ccText = $_POST['ccText'];
if (!isset($_POST['bccText'])) $bccText = ''; else $bccText = $_POST['bccText'];
if (!isset($_POST['nameText'])) $nameText = ''; else $nameText = $_POST['nameText'];
if (!isset($_POST['fromText'])) $fromText = ''; else $fromText = $_POST['fromText'];

if ($submit == "") {
    $title="Test Email Page";
    $announce="---";
}
else {
	if($fromText === "") die("No name!");
  $toText="youremail@yourdomain.com";
	$title="Test Email Page";
  $announce="Your Message has been Sent!";
	$header = "From: ".$fromText."\r\n";
//	$header .= "Cc: ".$ccText."\n";
	$header .= "Reply-To : ".$fromText."\r\n";
	$header .= "Return-Path : ".$fromText."\r\n";
	$header .= "X-Mailer: PHP\r\n";
	$header .= "MIME-Version: 1.0\r\n";
	$header .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
//	ini_set(sendmail_from,$fromText);  
	mail($toText, $subjectText, $msgText, $header, '-f'.$fromText);
//	ini_restore(sendmail_from);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title><?php echo($title)?></title>
<style type="text/css">
<!-- 
A:link { color: #999999; }
A:visited { color: #999999; }
A:hover {color: #0099ff;}
-->
</style>
<script type="text/javascript">
<!--
function check()
{
var at=document.getElementById("fromText").value.indexOf("@");
var eml=document.getElementById("fromText").value;
var nam=document.getElementById("nameText").value;
var alerttxt="";
var submitOK="true";

if (eml.length < 5 || at == -1)
    {
    alerttxt=alerttxt+"Please enter a valid e-mail address!\r\n";
    submitOK="false"
    //return false;
    }
if (nam.length < 3)
    {
    alerttxt=alerttxt+"Please enter your name.\r\n";
    submitOK="false"
    //return false;
    }
if (submitOK=="false")
    {
    alert(alerttxt);
    return false;
    }

}
// -->
</script>
</head>

<body bgcolor="#ddeedd">
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" summary="" width="580">
<tr><td align="center">

<?php
if ($submit != "") {
   	echo ("To: ".$toText."<br>\r\nSubject: ".$subjectText."<br>\r\n".$msgText."<br>\r\n".$header);
		}
?>

<p><b><font color="#000000" size="5">Test Email</font></b></p>
<font size="4" color="#000000">

<form method="POST" action="Email.php" onsubmit="return check();">
    <p><font size="3"><b>Name: <input type="text" name="nameText" id="nameText" size="46"></b></font></p>
    <p><font size="3"><b>Email: <input type="text" name="fromText" id="fromText" size="46"></b></font></p>
    <input type="hidden" name="subjectText" value="Web Mail">
    <p><font face="Arial" size="3"><b>Message Text:</b></font></p>
    <p><font face="Arial" size="3"><b><textarea rows="6" name="msgText" cols="60"></textarea></b></font></p>
    <p><font size="3"><b><input type="submit" value="submit" name="submit" style="font-family: Arial; font-size: 12pt; font-weight: bold"></b></font></p>
    <input type="hidden" name="state" value="1">
  </form>
  <b><font face="Arial" size="4" color="#e00000"><?php echo($announce)?></font></b><br><br>

</font>
</td></tr>
</table> 
</div>

</body>
</html>

Open in new window

Avatar of Nicholas_BlueStar
Nicholas_BlueStar

ASKER

sorry I am pretty novice when it comes to this.

The php you posted...does it have an html code to go along with it?

if I were to put this file as a .php in my root folder of my website directory - I need an html code in my contact page to actually fill in, right? I can post what I have for HTML in my current setup (although i doubt you need that)
My demo is self-contained.  It has all of the PHP, HTML, and even javascript to run and post to itself.  Run it as a test on your own server before you try modifying it.
Okay - so I created a Email.php file and copied all of your code. Changed the email address to my personal account to test. Uploaded the Email.php file to my testing server and then navigated to it. (i.e. test.mydomain.com/Email.php) - the page loaded. I entered my test info and hit submit.

It returned a message that said the message had been sent.

I have still not received the message. I have tried two different email addresses and still I am not receiving anything on my end...?
My hosting server is Hostmonster...does that make a difference?

I am thinking it is an issue on the hosting side now since your code isn't delivering messages either? Pretty confused, and for someone with my little knowledge I can't really get my head around what is going on.
Email delivery is a low priority service and sometimes it can take a while.

Some times you have to use an email address that is part of the hosting package, that is, using the same domain.  I don't know what Hostmonster's specific requirements are.  You may have to create an email address in your account and use that.
thanks for the help guys

I am trying to understand this but I am getting kinda lost.

I do not have a php.ini file on the server so I am not sure what I need to do there.

The one time i did get it to work it did reformat the "from" to the user@host### - I am still unsure what that really means.

Like I said I am not very knowledgable about this and would like someone to hold my hand and tell me what I need to change with my code in order for it to work.

How long can it take? its been at least 30+ minutes...
It's probably not being sent though I have had an email take 4 hours one time.  Look at the other links I posted from Hostmonster help pages.
I read them but even if that is one of my issues it would still send those emails just under a different username than expected.

I am not getting anything...assuming everything is correct and it is just in "waiting" - should I expect this delay every time?

I cannot have a long delay between the form being submitted and us getting it. I need to it be as instant as possible. It is going to be used as a part ordering form and we would need to respond within an hour of them sending it in most cases.
You may not have a choice in the 'username' if Hostmonster Requires you to use an email on the hosting.  I don't get that kind of delay when I use that page.  I just did a test on my Godaddy account and it was sent and received essentially instantly, less than a minute.
One of the other things you may encounter is that spam filters on email servers often check to see if the 'From:' email address can legitimately come from the IP address or domain that is sending the email.  I just had to change one of my spam settings to allow my email demo to send to one of my email addresses because of that.  It was sending to others but not the one.

There is SPF which is supposed to allow you to designate other IP addresses that are allowed to send 'as you'.  But since mail servers are having to block as much spam as they can, not all these things will be your choice.  You have to find out what works and use it.
Here is my form-to-email script.  It's also self-contained.  You can tailor it a bit for your own needs near the lines captioned CHANGE THESE.

This article may help some, too.
https://www.experts-exchange.com/Programming/Misc/A_10089-Trouble-Sending-Mail-from-Your-Script.html

<?php // RAY_form_to_email.php
error_reporting(E_ALL);


// SEND MAIL FROM A FORM


// REQUIRED VALUES ARE PREPOPULATED - CHANGE THESE FOR YOUR WORK
$from = 'NoReply@Your.org';
$subj = 'Contact Form';

// THIS IS AN ARRAY OF RECIPIENTS - CHANGE THESE FOR YOUR WORK
$to[] = 'You@Your.org';
$to[] = 'Her@Your.org';
$to[] = 'Him@Your.org';
$to[] = 'Ray.Paseur@Gmail.com';


// IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
if (!empty($_POST['e']))
{
    // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
    $safe_mail = clean_string($_POST['e']);
    $safe_name = clean_string($_POST['n']);
    $safe_fone = clean_string($_POST['t']);
    $save_idea = clean_string($_POST['i']);

    // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
    $content    = NULL;
    $content   .= "You have a New Query From $safe_name" . PHP_EOL . PHP_EOL;
    $content   .= "Tel No: $safe_fone" . PHP_EOL;
    $content   .= "Email: $safe_mail" . PHP_EOL;

    // SEND MAIL TO EACH RECIPIENT
    foreach ($to as $recipient)
    {
        if (!mail( $recipient, $subj, $content, "From: $from\r\n"))
        {
            echo PHP_EOL . "<br/>MAIL FAILED FOR $recipient";
        }
        else
        {
            echo PHP_EOL . "<br/>MAIL WORKED FOR $recipient";
        }
    }

    // PRODUCE THE THANK-YOU PAGE
    echo '<p>THANK YOU</p>' . PHP_EOL;
    die('TASK COMPLETE');
}


// A FORM TO TAKE CLIENT INPUT FOR THIS SCRIPT
$form = <<<ENDFORM
<form method="post">
Please enter your contact information
<br/>Email: <input name="e" />
<br/>Phone: <input name="t" />
<br/>Name:  <input name="n" />
<br/>Ideas? <textarea name="i"></textarea>
<br/><input type="submit" />
</form>
ENDFORM;

echo $form;


// A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str)
{
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    // REMOVE EXCESSIVE INPUT
    $str = substr($str, 0, 255);

    return trim($str);
}

Open in new window

HTH, ~Ray
Ray -

Can I use my own form html here?

// A FORM TO TAKE CLIENT INPUT FOR THIS SCRIPT
$form = <<<ENDFORM
<form method="post">
Please enter your contact information
<br/>Email: <input name="e" />
<br/>Phone: <input name="t" />
<br/>Name:  <input name="n" />
<br/>Ideas? <textarea name="i"></textarea>
<br/><input type="submit" />
</form>
ENDFORM;

echo $form;


I can post what the HTML looks like if that would be helpful.

This is self contained but can I "embed" this in an html page or do I need to still split it up into a mtl code that point to the php file?

The form needs to be on a page with other information.
Please read the PHP tutorial on forms here:
http://php.net/manual/en/tutorial.forms.php

That will show you the relationship between the HTML input controls and the behavior of the PHP script.  You should be able to use the script I posted as a guide or template to make your own.
Okay guys - I have made SOME progress. I have been able to successfully send the form with the below code. What I am having issues with is ADDING lines to fill out and getting it to send successfully.

Here is the HTML code
              <form action="contact.php" method="post" id="contactform_main">
                <ol>
                  <li>
                    <label for="name">Name*</label>
                    <input id="name" name="name" class="text"/>
                  </li>
                  <li>
                    <label for="email">Email*</label>
                    <input id="email" name="email" class="text" />
                  </li>
                  <li>
                    <label for="phone">Telephone*</label>
                    <input id="phone" name="phone" class="text"/>
                  </li>
                  <li>
                    <label for="subject">Vin / Body*</label>
                    <input id="subject" name="subject" class="text"/>
                  </li>
                  <li>
                    <label for="message">Message*</label>
                    <textarea id="message" name="message" rows="6" cols="50" ></textarea>
                  </li>
                  <li class="buttons">
                    <input type="submit" name="imageField" value="submit" class="send" />

Open in new window


Here is the PHP code
<?php

if(!$_POST) exit;

$email = $_POST['email'];


//$error[] = preg_match('/\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $_POST['email']) ? '' : 'INVALID EMAIL ADDRESS';
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."@"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email )){
	$error.="Invalid email address entered";
	$errors=1;
}
if($errors==1) echo $error;
else{
	$values = array ('name','email','message',);
	$required = array('name','email','message',);

	$your_email = "nicholas@bluestarbus.biz";
	$email_subject = "VIN / Body - ".$_POST['subject'];
	$email_content = "PART INQUIRY INFORMATION BELOW \n";

	foreach($values as $key => $value){
	  if(in_array($value,$required)){
		if ($key != 'subject' && $key != 'company') {
		  if( empty($_POST[$value]) ) { echo 'PLEASE FILL IN REQUIRED FIELDS'; exit; }
		}
		$email_content .= $value.': '.$_POST[$value]."\n";
	  }
	}

	if(@mail($your_email,$email_subject,$email_content)) {
		echo 'Message sent!';
	} else {
		echo 'ERROR!';
	}
}
?>

Open in new window


I cannot add anything to line 15&16 where it has $values & $required.

I have tried to add 'telephone' to both lines to make a telephone number required.

When I do that - I get the response "Please fill in required fields" line...can someone explain how/what I need to do in order to post that information in the form?

Also - as it stands right now, I do not receive the telephone line (even when it is filled out) in my email I get.

Can someone "hold my hand" and tell me what I need to add to my php/html to get those lines to work properly.

I am getting the from as the email@host###.hostmonster.com - which is the least of my worries at this point.
There is a relationship between the content of the HTML form and the data that is presented to the PHP action script.  The name attribute in the HTML input control becomes the key of the request variable (either $_POST or $_GET).  That is why I suggested you read the introductory tutorial on forms.

Consider this from the HTML form:

<input name="phone" />

Whatever the client fills in will appear in $POST["phone"]

It will not appear in $_POST["telephone"]

Does that help clear it up?
That makes sense Ray, however, if I add "phone" it will not work.

Line 15&16 in PHP code reads:

      $values = array ('name','email','message',);
      $required = array('name','email','message',);

If i change it to

      $values = array ('name','email','message','phone',);
      $required = array('name','email','message','phone',);

I get an error that states "PLEASE FILL IN REQUIRED FIELDS" even when I do fill in the telephone line on the website.

Im pretty dumb about this, but adding that 'phone' to both values and required would make it so that the line is required and that it will post to the email and send the information they entered into that field?
Same issue (I think) when trying to change the "subject" to "vin" in the HTML form.

If I change the Vin / Body area in html to "vin" instead of "subject" (and update all the info in the PHP file to "vin" from "subject") I just get a blank area when the email comes in. If I leave the "label" "input" & "name" (But change what the end user sees to Vin / Body) as "subject" then it DOES post to the e-mail... I would assume changing those three (label, input & name) to "vin" as well as changing line 19 & 24 in the php file from 'subject' to 'vin' would allow it to post correctly when sending the email. It does not...it leaves that area blank when I receive a test email.
sorry for all the comments but I have one question.

this line:

            if ($key != 'subject' && $key != 'company') {

I don't see a "company" line, code, input, etc. Can you explain what that line is doing/does?

Like I said, the form works right now (with what I have posted above) but there is nothing about "company" anywhere???
Where did you get this piece of programming?  It has a distinct "code smell" that it is either very old and/or was written by someone who is not very knowledgeable about PHP.

It could be that some if statements need else statements.  Not sure about that, but I will try to document a section of the code to see if we can figure it out.  It's hard to follow the logic because some of it just doesn't make any sense, sorry.  I am not sure this is exactly what the program says, but at least it's better spaced so we can look at one line at a time.  Basically, if it encounters any error condition, it stops checking, sends you a message that it failed (but does not tell you why) and dies on the spot without considering any other parts of the request data.

$values   = array('name','email','message');
$required = array('name','email','message');

// ITERATE OVER THE VALUES ARRAY, CHOOSING ONE NUMERIC INDEX AND ONE STRING DATA ELEMENT
foreach($values as $key => $value)
{
    // IF THE $value CAN BE FOUND IN THE $required ARRAY
    if(in_array($value,$required))
    {
        // THIS WILL ALWAYS BE TRUE BECAUSE THE $key VARIABLE IS A NUMBER
        if ($key != 'subject' && $key != 'company') 
        {
            // THIS WILL CHECK TO SEE THAT THE POST REQUEST HAS AN EMPTY VALUE
            if( empty($_POST[$value]) ) 
            { 
                // SEND A MESSAGE
                echo 'PLEASE FILL IN REQUIRED FIELDS'; 
                
                // IMMEDIATELY END PROCESSING
                exit; 
            } /* END IF empty() */
        } /* END IF($key) */
    // ADD THE VALUE STRING AND THE CONTENT OF THE POST REQUEST TO THE $email_content STRING
    $email_content .= $value.': '.$_POST[$value]."\n";
    } /* END IF in_array() */
} /* END foreach() */

Open in new window

Executive summary: You probably want to throw this away and start over with a new template.
This is a template that I downloaded that already had a "contact.html" and a "contact.php"

I really like the way it "functions" when the end user hits submit. It "vanishes" AND is replaced with a "Message Sent". Which allows the end user to stay on the same page, NOT have the form available to fill out again and resend AND also gives them a confirmation that the message sent.

I don't believe I am smart enough to come up with something else that works any better.

I would like:
Name*
School / Business*
Telephone*
E-mail*
Vin / Body #*
Part # (optional)
Part Description*

And I would like the email that is sent to me to read:
From: Name They Entered and/or The E-mail they entered
Subject: Parts Inquiry
Body Of Email:
    Name:
    School:
    Telephone #:
    E-Mail:
    Vin / Body #:
    Part #:
    Part Description:

Can you help me with the HTML/PHP code for what I want?
I have found other PHP code that "works" but it does not function like the one I am trying to modify.

if you want to see how the code I have right now "works" inside a website look below and fill out all the info to see what happens. This "action" or "function" or whatever is important to me.

http://test.bluestarbussales.com/contact.html
In the demo that I posted, there is an entry in the javascript and in the PHP for each of the <input> variables that is used.  I would never and have never used a 'foreach' loop to blindly get all of the POST variables.  You might think it's more work my way.  It's not more work than having to wade thru a bunch of code trying to figure out what's wrong.
@ Dave

I am not against "more" lines of code if it makes sense, easy to edit, and functions the way my current setup does.

It throws me for a loop when it is all self contained...I am not sure how I could "use" the code in my website to "look" and "act" the same way as it does now...
Just for your info, here is what my email looked like once you just submitted your "feedback"

User generated image
Having things "self-contained" should not cause you any trouble, just strip out the parts you don't want.  You can put things like that into a separate script.

This is the form from the web page.

              <form action="contact.php" method="post" id="contactform_main">
                <ol>
                  <li>
                    <label for="name">Name*</label>
                    <input id="name" name="name" class="text"/>
                  </li>
                  <li>
                    <label for="email">Email*</label>
                    <input id="email" name="email" class="text" />
                  </li>
                  <li>
                    <label for="phone">Telephone*</label>
                    <input id="phone" name="phone" class="text"/>
                  </li>
                  <li>
                    <label for="subject">Vin / Body*</label>
                    <input id="subject" name="subject" class="text"/>
                  </li>
                  <li>
                    <label for="message">Message*</label>
                    <textarea id="message" name="message" rows="6" cols="50" ></textarea>
                  </li>
                  <li class="buttons">
                    <input type="submit" name="imageField" value="submit" class="send" />
                    <!--<input type="image" name="imageField" id="imageField" src="images/sub.png" class="send" />-->
                    <div class="clr"></div>
                  </li>
                </ol>
              </form>

Open in new window

Given that, I'll try to show you how you might process the request.
Please see: http://www.laprbass.com/RAY_temp_nicholas_bluestar.php

It still needs your styling, but at least the PHP functionality is organized in a way that will let you add your own edits to the input request.  In this example, "contact.php" is from the top of the script through line 53.

<?php // RAY_temp_nicholas_bluestar.php
error_reporting(E_ALL);

// THE NAMED FIELDS
$fields = array
( 'name'
, 'email'
, 'phone'
, 'subject'
, 'message'
)
;

// THE REQUIRED FIELDS (NOTE PHONE IS NOT REQUIRED)
$required = array
( 'name'
, 'email'
, 'subject'
, 'message'
)
;
// IF THE FORM REQUEST HAS BEEN POSTED
if (!empty($_POST))
{
    // TEST FOR REQUIRED FIELDS
    $error = array();
    foreach ($required as $field)
    {
        // DO WHATEVER YOU WANT TO HERE TO SANITIZE THE INPUT
        $_POST[$field] = trim($_POST[$field]);

        // AFTER SANITIZING INPUT, IS THE VALUE STILL ACCEPTABLE?
        if (empty($_POST[$field])) $error[] = $field;
    }

    // WERE ANY ERRORS FOUND?
    if (!empty($error))
    {
        $message = 'PLEASE PROVIDE VALUES FOR: ' . implode(', ', $error);
        echo $message;
    }

    // NO ERRORS WERE FOUND
    else
    {   // USE THESE FIELDS TO CONSTRUCT THE EMAIL MESSAGE
        foreach ($fields as $field)
        {
            $message = PHP_EOL . $field . ': ' . $_POST[$field];
        }
        mail('you@your.org', 'EMAIL FROM WEB SITE', $message);
        die("THANKS -- YOUR EMAIL HAS BEEN SENT");
    }
}

// CREATE THE FORM USING HEREDOC NOTATION
$form = <<<EOD
              <form action="" method="post" id="contactform_main">
                <ol>
                  <li>
                    <label for="name">Name*</label>
                    <input id="name" name="name" class="text"/>
                  </li>
                  <li>
                    <label for="email">Email*</label>
                    <input id="email" name="email" class="text" />
                  </li>
                  <li>
                    <label for="phone">Telephone*</label>
                    <input id="phone" name="phone" class="text"/>
                  </li>
                  <li>
                    <label for="subject">Vin / Body*</label>
                    <input id="subject" name="subject" class="text"/>
                  </li>
                  <li>
                    <label for="message">Message*</label>
                    <textarea id="message" name="message" rows="6" cols="50" ></textarea>
                  </li>
                  <li class="buttons">
                    <input type="submit" name="imageField" value="submit" class="send" />
                    <!--<input type="image" name="imageField" id="imageField" src="images/sub.png" class="send" />-->
                    <div class="clr"></div>
                  </li>
                </ol>
              </form>
EOD;
echo $form;

Open in new window

HTH, ~Ray
DISREGARD #2 READING THE PHP I THINK I KNOW WHAT I NEED TO ADD. STILL NOT SURE ABOT #1 THOUGH


Hey Ray - Thanks for all your help.

Using your code - it sends successfully, however, a couple of things.

1) It does not "vanish" when I click submit. It just pops up above and says message sent. (See picture attached).

User generated image
2) I only receive the "message" part in the email.

User generated image
This is my updated PHP and it seems to have broken something...I am no longer getting emails after I changed this section of the php file.

    {   // USE THESE FIELDS TO CONSTRUCT THE EMAIL MESSAGE
        foreach ($fields as $field)
        {
            $name = PHP_EOL . $field . ': ' . $_POST[$field];
                   $email = PHP_EOL . $field . ': ' . $_POST[$field];
                   $phone = PHP_EOL . $field . ': ' . $_POST[$field];
                   $subject = PHP_EOL . $field . ': ' . $_POST[$field];
                   $message = PHP_EOL . $field . ': ' . $_POST[$field];
        }
        mail('nicholas@bluestarbus.biz', 'PARTS INQUIRY', $name, $email, $phone, $subject, $message);
        die("THANKS -- YOUR EMAIL HAS BEEN SENT");
    }
}
The "vanish" part is (probably) jQuery.  I didn't study it very carefully and it could be an IFrame trick, too.

Change near line 43 in my script as follows, to use string concatenation:
    // NO ERRORS WERE FOUND
    else
    {   
        $message = NULL;
        
        // USE THESE FIELDS TO CONSTRUCT THE EMAIL MESSAGE
        foreach ($fields as $field)
        {
            $message .= PHP_EOL . $field . ': ' . $_POST[$field];
        }
        mail('you@your.org', 'EMAIL FROM WEB SITE', $message);
        die("THANKS -- YOUR EMAIL HAS BEEN SENT");
    }

Open in new window

Our messages crossed.  Good news: All of the PHP functions are documented in the online man pages.  Example here.  If you read that you will see that the mail() function cannot handle all of those arguments separately; they have to be put together into a message body.
http://php.net/manual/en/function.mail.php

Some resources that may be helpful if you're new to PHP:
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
Thanks for the update Ray - but as I have said, I am not technically gifted with this stuff.

I read the first link you posted and still can't figure out what exactly I need to change/update to make it work. I kinda understand that the way I formatted my lines for what I want displayed in my email is wrong. I, however, did not understand what to change to make it work with that information...can you give me an example with multiple subjects (i.e. message & phone).

I am a very visual learner. Once I "see" how it should look I can normally decipher what needs to be done...Sorry for all the questions and issues - I am trying to learn as much as I can.
I am going to recommend that you step away from this problem and hire a professional programmer to help you get it working.  This thread has gone on too long and you're not "getting it" at a level that will enable you to make much progress.  If you want to learn how to use PHP and other web technologies, head over to this article and get started, but don't expect that you can write PHP scripts without learning PHP -- that would be like trying to write German poetry without learning German!  It takes some time and structured study, and that's why I think you may be better off hiring a pro instead of trying to become a pro in the process of doing this exercise.

Here is the script.  I just tested it and it looks OK to me.  Plug in your email address on line 53 and try it for yourself.  And best of luck with your project! ~Ray
<?php // RAY_temp_nicholas_bluestar.php
error_reporting(E_ALL);

// THE NAMED FIELDS
$fields = array
( 'name'
, 'email'
, 'phone'
, 'subject'
, 'message'
)
;

// THE REQUIRED FIELDS (NOTE PHONE IS NOT REQUIRED)
$required = array
( 'name'
, 'email'
, 'subject'
, 'message'
)
;
// IF THE FORM REQUEST HAS BEEN POSTED
if (!empty($_POST))
{
    // TEST FOR REQUIRED FIELDS
    $error = array();
    foreach ($required as $field)
    {
        // DO WHATEVER YOU WANT TO HERE TO SANITIZE THE INPUT
        $_POST[$field] = trim($_POST[$field]);

        // AFTER SANITIZING INPUT, IS THE VALUE STILL ACCEPTABLE?
        if (empty($_POST[$field])) $error[] = $field;
    }

    // WERE ANY ERRORS FOUND?
    if (!empty($error))
    {
        $message = 'PLEASE PROVIDE VALUES FOR: ' . implode(', ', $error);
        echo $message;
    }

    // NO ERRORS WERE FOUND
    else
    {
        $message = NULL;

        // USE THESE FIELDS TO CONSTRUCT THE EMAIL MESSAGE
        foreach ($fields as $field)
        {
            $message .= PHP_EOL . $field . ': ' . $_POST[$field];
        }
        mail('You@Your.org', 'EMAIL FROM WEB SITE', $message);
        die("THANKS -- YOUR EMAIL HAS BEEN SENT");
    }
}

// CREATE THE FORM USING HEREDOC NOTATION
$form = <<<EOD
              <form action="" method="post" id="contactform_main">
                <ol>
                  <li>
                    <label for="name">Name*</label>
                    <input id="name" name="name" class="text"/>
                  </li>
                  <li>
                    <label for="email">Email*</label>
                    <input id="email" name="email" class="text" />
                  </li>
                  <li>
                    <label for="phone">Telephone*</label>
                    <input id="phone" name="phone" class="text"/>
                  </li>
                  <li>
                    <label for="subject">Vin / Body*</label>
                    <input id="subject" name="subject" class="text"/>
                  </li>
                  <li>
                    <label for="message">Message*</label>
                    <textarea id="message" name="message" rows="6" cols="50" ></textarea>
                  </li>
                  <li class="buttons">
                    <input type="submit" name="imageField" value="submit" class="send" />
                    <!--<input type="image" name="imageField" id="imageField" src="images/sub.png" class="send" />-->
                    <div class="clr"></div>
                  </li>
                </ol>
              </form>
EOD;
echo $form;

Open in new window

Thanks for trying Ray.

This is one script on one page that I am not going to pay a professional to come in and write it for me. I have everything else completed and can't imagine spending hundreds to have a professional come in so that someone can send an email to me through our website. Seems ridiculous for such a small function.

Ill look at what you posted and try to get something that works, since nothing to this point has done something so very simple.
Again

I just want to know what the code should look like if I wanted to include all the lines from the phone and not just the "message" line. If I could get that figured out then Im pretty much set (aside from it not emailing "from" correctly and not "vanishing" when submitting).

        // USE THESE FIELDS TO CONSTRUCT THE EMAIL MESSAGE
        foreach ($fields as $field)
        {
            $message .= PHP_EOL . $field . ': ' . $_POST[$field];
        }
        mail('You@Your.org', 'EMAIL FROM WEB SITE', $message);
        die("THANKS -- YOUR EMAIL HAS BEEN SENT");
    }
Try the script posted here.  It worked OK for me.

The trouble I think you're having with this is that it's not "one script on one page" nor is it "such a small function" at all.  It looks simple to you, but you don't see it with the eyes of a developer.  There are five areas of technology involved in the presentation and processing.

Client side: HTML, CSS, JavaScript.  Server side: PHP, possibly a data base, and the hugely complicated mess that is the internet email system.  The details of client/server protocols may be something you want to understand.  You may want to consider what would happen if there were a hiccup in the email system because it happens all the time.  If you have a data base that records all of the inquiries, you could avoid losing the client's data, even if your ISP decided to "test out" a new spam filter or the Suhosin extension or some other hare-brained thing.

It's these sorts of design-level considerations that you would expect to get from a professional.  Getting the PHP and JavaScript right is something anybody can do even if they aren't experienced developers -- you just keep plugging away, maybe with a book in hand, and eventually you'll get something to work the way you want.
That script does work, Ray. But it only sends me the "message" part of the form that was filled out. My issue with understanding is what needs to be changed so ALL of the fields are captured and sent through e-mail - not just the "message" field. That is the part that I don't understand. The page you said to look at for assistance has

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

to send mail...that looks nothing like your line

            $message .= PHP_EOL . $field . ': ' . $_POST[$field];
Please, please step back from this project and take a little while to get some understanding of the fundamentals of computer programming in general and PHP in particular.  If you give yourself a month of structured study now, you will suddenly be a year ahead of trial-and-error learning, I promise.  It's a huge waste of your time to try to pick this knowledge up in a haphazard question and answer process.

You wrote, "That script does work, Ray. But it only sends me the "message" part..." however that is a factually inaccurate statement.  The most recent version of the script sends all of the fields.  You can install it and run it to see the moving parts in action.  Most of the time when I post a script here at EE I test it for functionality, and I tested that one.  Perhaps you were running an older version of the script?

I'll try to answer your latest question then I have to sign off because this is no longer a question that has an answer, so much as a plea for line-by-line help with a fairly advanced exercise in application development.  You will get better results faster if you hire a professional developer.  As the great firefighter Red Adair said, "If you think it's expensive to hire a professional, just wait till you hire an amateur!"  I'm glad to answer questions for free, so here you go.

This is the "man page" template of the PHP mail() function:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

This is an assignment of variables using string concatenation:
$message .= PHP_EOL . $field . ': ' . $_POST[$field];

Those two statements are not quite as different as fish and bicycles, but almost.

The instruction corresponding to the man page:
mail('You@Your.org', 'EMAIL FROM WEB SITE', $message);

The mapping of variables into the mail template:
$to == 'You@Your.org'
$subject == 'EMAIL FROM WEB SITE'
$message == $message
[, string $additional_headers [, string $additional_parameters ]]
optional and omitted

Here are two instructions that look very similar but have very different meanings:
$message  = PHP_EOL . $field . ': ' . $_POST[$field];
$message .= PHP_EOL . $field . ': ' . $_POST[$field];


The difference is the dot (period) before the equal sign.  It changes the assignment operator (the single equal sign) into the concatenating assignment operator.  PHP only has two string operators.  These are the sorts of things you will learn if you take a little bit of time to study the language.

Best regards, and best of luck with your project, ~Ray
Thanks for your help Ray.

I tested your latest code, while I do get all the subject lines, nothing populates the telephone line no matter what I put in it.

At this point I think I am just going to pay for a form to be built for me (MachForm). Can you recommend anything better than Machform?

For $50 I can have a code built for me...It "looks" a lot better than what I have been dealing with. You think its worth it Ray?
I don't think you actually tested my latest code; I tested it and the phone came through perfectly, something got changed if the phone is not coming to the action script.  Since you're having trouble integrating this, I think you might be better off with Machform.  I've never used it, but it seems like it could be worth a try.
Weird. I copied your code line for line???

Ill try again and see what happens. It was showing the "telephone" line in the email, just not populated. Weird. Ill give it one last shot. Again, thanks for you patience Ray
The key things to look for are these:

The name= attribute in the HTML form <input> control will become the array key in the request ($_GET or $_POST).  The script must match the input to the expected name/key in order to find and process the client inputs.
Ray...

after HOURS and HOURS of staring at this stupid code, I have figured it out.

Like I said, I am pretty novice when it comes to coding.

It ended up being a .js file that had conditions regarding my contact form.

I updated that .js file and it is now working without issue.

Thanks for all the help and time you spent on this. I appreciate it!
Ray - I would like to give you credit for all the time you spent on this but I don't have one solution that is "correct" to my specific issue. (i.e. ended up being a simple .js file I needed to edit to make the form work correctly).

How should I address this and close the question?
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Haha yeah no joke

I didn't see any mention about a javascript that it was pointing to.

I ended up just reading EVERY line of code MANY times before I gave up and started reading EVERY line of code from all the other .js and .css files associated with that contact page!

Terrible + Great feeling all at the same time. It was a 30 second fix with javascript :) haha

anyway - Like I said, I want to give you credit for all your help. What do you think should be the "accepted answer"?
Wasn't the "right" answer but without Ray's help I would have never been able to pinpoint what was going on.