1

I have fairly basic knowledge with HTML and CSS, having built my site from scratch. I was using JotForm in an iFrame as my contact form but want to change this to a PHP form so I am not reliant on these guys and I have more control over the look of the form.

I did initially have the form sending an email with blank fields - I tried to fix this and have now completely messed up.

Any help is very much appreciated.

Here is my HTML for the form which is set out in a table;

    <table width="400" border="0" align="left" cellpadding="5" id="form">

  <tr>
<th width="134" scope="row" align="right">NAME</th>
<th width="240" scope="row">
<form name="name" method="post" action="contact.php">
  <span id="sprytextfield1">
  <input type="text" name="name" id="name" value="<?php print "$nameField"; ?>">
  <span class="textfieldRequiredMsg">A value is required.</span><spanclass="textfieldInvalidFormatMsg">Invalid format.</span></span>
</form></th>
</tr>

<tr>
<th scope="row">&nbsp;</th>
<th scope="row">&nbsp;</th>
</tr>

<tr>
<th scope="row" align="right">EMAIL</th>
<th scope="row">
<form name="email" method="post" action="contact.php">
  <span id="sprytextfield2">
  <input type="text" name="email" id="email" value="<?php print "$emailField"; ?>">
  <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span>
</form></th>
</tr>

<tr>
<th scope="row">&nbsp;</th>
<th scope="row">&nbsp;</th>
</tr>
<tr>
<th height="128" scope="row" align="right">MESSAGE</th>
<th scope="row">
<form name="message" method="post" action="contact.php">
  <span id="sprytextarea1">
  <textarea name="message" id="message" cols="45" rows="5"><?php print "$messageField"; ?></textarea>
  <span class="textareaRequiredMsg"><br>
  A value is required.</span></span>
</form></th>
</tr>
<tr>
<th scope="row">&nbsp;</th>
<th scope="row">&nbsp;</th>
</tr>
<tr>
<th scope="row">&nbsp;</th>
<th scope="row"><form name="submit" method="post" action="contact.php">
  <input type="hidden" name="parse_var" id="parse_var" value="contactform">
  <input type="submit" name="submit" id="submit" value="SEND MESSAGE">
</form></th>
</tr>
<tr>
<th scope="row">&nbsp;</th>
<th scope="row"><?php print "$sent"; ?></th>
</tr>
</table>

and my PHP:

<?php

        if ($_POST['parse_var'] == "form") {

    $emailTitle = 'New Contact Form Message';
    $yourEmail = 'charlotte@charlottemay.co.uk';

    $emailField = $_POST['email'];
    $nameField = $_POST['name'];
    $messageField = $_POST['message'];

    $body = <<<EOD
    <br><hr><br>
    Email: $emailField <br />
    Name: $nameField <br />
    Message: $messageField <br />

    EOD;

    $headers = "From: $emailField\r\n";
    $headers .= "content-type: text/html\r\n";
    $success = mail("$yourEmail", "$emailTitle", "$body", "$headers");

    $sent = "thankyou, your message has been successfully sent x";
    }

    ?>

2 Answers2

0

Ok, here is functional, BUT not GOOD form, every field should be validated/checked (required fields, fields format, etc, etc...).

But, this will work. I have cleaned up your HTML code, please see where you made mistakes...

As mentioned, your HTML structure was main problem - you had multiple FORM tags all arround - for every field of form - this is not proper way, please see basic examples of HTML for php form...

Code:

<?php 

    if($_POST['parse_var']=='contactform') {

    $emailTitle = 'New Contact Form Message';
   $yourEmail = 'charlotte@charlottemay.co.uk';


    $emailField = $_POST['email'];
    $nameField = $_POST['name'];
    $messageField = $_POST['message'];



    $body = "
    <br><hr><br>
    Email: $emailField <br />
    Name: $nameField <br />
    Message: $messageField <br />

 ";

    $headers = "From: $emailField\r\n";
    $headers .= "content-type: text/html\r\n";
    $success = mail("$yourEmail", "$emailTitle", "$body", "$headers");

    $sent = "thankyou, your message has been successfully sent x";

    }


    ?>

<table width="400" border="0" align="left" cellpadding="5" id="form">

  <tr>
<th width="134" scope="row" align="right">NAME</th>
<th width="240" scope="row">
<form name="name" method="post" action="contact.php">
  <span id="sprytextfield1">
  <input type="text" name="name" id="name" value="">
  <span class="textfieldRequiredMsg">A value is required.</span></span>
</th>
</tr>

<tr>
<th scope="row">&nbsp;</th>
<th scope="row">&nbsp;</th>
</tr>

<tr>
<th scope="row" align="right">EMAIL</th>
<th scope="row">

  <span id="sprytextfield2">
  <input type="text" name="email" id="email" value="">
  <span class="textfieldRequiredMsg">A value is required.</span></span>
</th>
</tr>

<tr>
<th scope="row">&nbsp;</th>
<th scope="row">&nbsp;</th>
</tr>
<tr>
<th height="128" scope="row" align="right">MESSAGE</th>
<th scope="row">
  <span id="sprytextarea1">
  <textarea name="message" id="message" cols="45" rows="5"></textarea>
  <span class="textareaRequiredMsg"><br>
  A value is required.</span></span>
</th>
</tr>
<tr>
<th scope="row">&nbsp;</th>
<th scope="row">&nbsp;</th>
</tr>
<tr>
<th scope="row">&nbsp;</th>
<th scope="row">
  <input type="hidden" name="parse_var" id="parse_var" value="contactform">
  <input type="submit" name="submit" id="submit" value="SEND MESSAGE">
</form></th>
</tr>
<tr>
<th scope="row">&nbsp;</th>
<th scope="row"><?php print "$sent"; ?></th>
</tr>
</table>

P.S. Use it at your own risk. :) To avoid spamming, empty forms sending - fields must be validated - there are tons of tutorials about this, check some of them.

sinisake
  • 11,240
  • 2
  • 19
  • 27
  • Thankyou so much! I am going to have a good read of this and learn from my mistakes -I'll also look into the validated forms. **thankyou** – Charlotte May Jul 08 '13 at 21:01
0

First of all refactor your html by replacing the tables with <div> and <p>. Forms are tabular but tables shouldn't be used for general layouting.

Also try to avoid html inside php scripts. Use seperate views instead. A PHP Framework might help you out. Have a look at Codeginiter.

Think of the <form> tag as a div container. Wrap the whole form with it. So start with <form> then place all form related elements inside and close with </form> at the end. This makes the form part in an html document stand out, so it'll be easier for you to work with (readability).

I have changed your code examples:

The form HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Form Page</title>
    <!-- Your header items like meta and link for css stylesheets -->
</head>
<body>

    <div id="container">
        <form id="form-id" action="contact.php" method="POST">
            <input id="parse_var" type="hidden" name="parse_var" value="contactform">

            <div>
                <label for="name">Name</label>
                <input id="name" type="text" name="name" value="<?php echo $nameField; ?>">
                <?php if (empty($nameField)) echo '<span class="textfield requiredmsg">A value is required.</span>'; ?>
                <?php if (empty($nameField)) echo '<span class="textfield invalidformatmsg">Invalid format.</span>'; ?>
            </div>

            <div>
                <label for="email">E-Mail</label>
                <input id="email" type="text" name="email" value="<?php echo $emailField; ?>">
                <?php if (empty($emailField)) echo '<span class="textfield requiredmsg">A value is required.</span>'; ?>
                <?php if (empty($emailField)) echo '<span class="textfield invalidformatmsg">Invalid format.</span>'; ?>
            </div>

            <div>
                <label for="message">Message</label>
                <textarea id="message" name="message"><?php echo $messageField; ?></textarea>
                <?php if (empty($messageField)) echo '<span class="textfield requiredmsg">A value is required.</span>'; ?>
            </div>

            <div class="form-controls">
                <input type="submit" name="submit" id="submit" value="Send message">
            </div>
        </form>
    </div>

</body>
</html>


Regarding your PHP code, check this out:

<?php

// Create a view load function
function loadView($view)
{
    // Change this to where you save the view files
    $viewPath = '/'.$view.'.php';

    // Check if the requested view exists
    if ( ! file_exists($viewPath)) return false;

    // This will put the view source in a variable 
    // without flushing to the screen (like echo / print)
    ob_start();
    include $viewPath;
    $buffer = ob_get_contents();
    @ob_end_clean();

    return $buffer;
}

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['parse_var']))
{
    // Differentiate between forms
    if ($_POST['parse_var'] == 'contactform')
    {
        // Check if all required data was submitted
        if (isset($_POST['name'], $_POST['email'], $_POST['message']) 
            && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
        {
            // Mail Message Settings
            $emailTitle = 'New Contact Form Message';
            $yourEmail  = 'charlotte@charlottemay.co.uk';

            // Get the form data (remember to secure user input against e.g. CSRF)
            $emailField   = $_POST['email'];
            $nameField    = htmlentities($_POST['name']);
            $messageField = strip_tags($_POST['message']);

            // Load the email body view. The variables above 
            // will be accessible in the view.
            $body = loadView('email_body');

            // Set the mail headers
            $headers  = "From: $emailField\r\n";
            $headers .= "Content-type: text/html\r\n";

            // Send the message - I highly recommend you to use something like SwiftMailer!
            $mail = mail($yourEmail, $emailTitle, $body, $headers);

            // Check if the mail was sent
            if ($mail)
            {
                echo 'Sweet! Your message has been successfully sent.';
            }
            else
            {
                echo 'Whoops! The message was not sent.';
            }
        }
        else
        {
            // Here you could return an error message
        }
    }
}


Note that I changed the double " quotes into single ' quotes. Why? See this SO question: https://stackoverflow.com/a/3446286/2493918 .

I highly recommend you to use something like SwiftMailer to send emails with PHP! Using the native mail() function might not always work as expected and most of the sent mails will be thrown in the recipients SPAM folder (like gmail and such).

Read through the code comments to learn more about the changes I made.

A good resource to learn more what PHP has to offer is the PHP Documentation which can be found here: For example the ob_start() function http://www.php.net/manual/en/function.ob-start.php .

Happy coding!

Community
  • 1
  • 1
Markus Hofmann
  • 3,427
  • 4
  • 21
  • 31