Avatar of Alison Cox
Alison Cox

asked on 

Send email using HTML and PHP in separate file

I have this all working (email sends just fine), except that on the HTML page I want the message "Thank you for sending us a message. We will get back to you as soon as possible." to appear on the contact-us.html.   What have I missed?  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Contact</title>
  <body>

    <header id="header">
        
        </header>


    <section id="contact-page">
        <div class="container">
            <div class="center">        
                <h2>Send A Message</h2>
                <p class="lead"></p>
            </div> 
            <div class="row contact-wrap"> 
                <div class="status alert alert-success" style="display: none"></div><div class="content">
                
                
                  <form  class="contact-form" name="contact-form" action="sendemail.php"   method="post">
                    <div class="col-sm-5 col-sm-offset-1">
                        <div class="form-group">
                            <label>Name *</label>
                            <input type="text" name="name" class="form-control" required="required">
                        </div>
                        <div class="form-group">
                            <label>Email *</label>
                            <input type="text" name="email" class="form-control" required="required">
                        </div>             
                    </div>
                    <div class="col-sm-5">
                        <div class="form-group">
                            <label>Subject *</label>
                            <input type="text" name="subject" class="form-control" required="required">
                        </div>
                        <div class="form-group">
                            <label>Message *</label>
                            <textarea name="message"  required="required" class="form-control" rows="8"></textarea>
                        </div>                        
                        <div class="form-group">
                            <input type="submit"  class="btn btn-primary btn-lg"  >
                        </div>
                    </div>
                </form> 
                  </div><!--/.row-->
        </div><!--/.container-->
    </section><!--/#contact-page-->

</body>
</html>

Open in new window


PHP:
<?php 

$status = array(
		'type'=>'success',
		'message'=>'Thank you for sending us a message. We will get back to you as soon as possible. '
	);
  header('Location: contact-us.html','Content-Type: application/json');
    $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 = 'myemail@domain.com';

    $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;

    $success = @mail($email_to, $subject, $body, 'From: <'.$email.'>');
    echo $status;
  
    die
    ?>

Open in new window

HTMLPHP

Avatar of undefined
Last Comment
Alison Cox
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html

The PHP script should be modified to produce this message.  Remove the header().  Go down to where it says echo $status (this probably is never executed because of the header() causing a redirection) and put the message you want in an echo statement there.

Also, remove the @ from all of the function calls, so you can find out if any of them are failing and correct the failures.  Remove the die statement.  Remove the ?> close PHP tag.  Avoid that tag whenever you possibly can.

Once you are seeing the message, then you can flesh out a nice looking HTML document with appropriate content and styling.  Most of us who have done this have put the HTML and PHP together into a single script file.  A single script file makes it easier to keep our work organized.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Here's my teaching example of a single script file that takes HTML form input and sends the input out via email.
<?php // demo/form_to_email.php
/**
 * Use PHP to Send Email from an HTML Form
 */
error_reporting(E_ALL);


// 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';


// 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']);
    $safe_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;
    $content .= "Idea: $safe_idea" . 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 (NOTE 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

Avatar of Alison Cox
Alison Cox

ASKER

Thanks all!  I ended up using the Ajax solution and it was perfect; but I'm going to also play with your last suggestion, Ray, because now I'm finally understanding how it works together and love the results.  Thanks bot
PHP
PHP

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

125K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo