Solved

PHP contact form not working

Posted on 2012-03-28
4
568 Views
Last Modified: 2012-03-29
I have a php contact form here: http://www.bdcwebdesign.com/?a=Colorado-Wyoming_Contact-Us

I was making some changes to it today to make the text disappear, but when I was testing I realized I wasn't receiving the emails being sent by the form. I rolled back the changes, but it still isn't working.

Honestly, it has been a while since I received an email from this form so I don't know exactly when it broke. Any help would be nice.

Here is my code:

<?php

if(isset($_POST['name'])) { $name = $_POST['name']; } else { $name = ''; }
if(isset($_POST['email'])) { $email= $_POST['email']; } else { $email = ''; }
if(isset($_POST['phone'])) { $phone= $_POST['phone']; } else { $phone = ''; }
if(isset($_POST['message'])) { $message= $_POST['message']; } else { $message = 'Your message here'; }

$form = "
<form method='post' />
<p>
*Name:
</p>
<p>
<input type='text' name='name' value='$name' />
</p>

<p>
Email:
</p>
<p>
<input type='text' name='email' value='$email' />
<p>
<p>
*Phone:
</p>
<p>
<input type='text' name='phone' value='$phone' />
</p>
<p>
*Message:
</p>
<p>
<textarea onclick='cleatTextAtea(this)' name='message' cols='40' rows='10' >$message</textarea>
</p>
<p>
<input type='submit' name='submit' value='Submit' class='form_submit' />
</p>
<p>
*required fields
</p>
</form>";

if(isset($_POST['submit'])) {

    $errors = array();
    if(strlen( $_POST['name'] ) == 0) { $errors[] = "Please provide your name"; }
    if(strlen( $_POST['phone'] ) == 0) { $errors[] = "Please provide your phone number"; }
    if(strlen( $_POST['message'] ) == 0 || $_POST['message'] == 'Your message here') { $errors[] = "Please enter a message"; } 

    if(count($errors) == 0) {
        $header = 'From: ' .$_POST['email'] .'\r\nContent-type: text/plain; charset=iso-8859-1\r\n';
        $body = 'Name:: '. $_POST['name'];
        $body .= '\nEmail:: '. $_POST['email'];
        $body .= '\nPhone:: '. $_POST['phone'];
        $body .= '\nMessage:: '. $_POST['message'];
        $body = wordwrap($body,70);
        $send = mail('info@bdcwebdesign.com', 'Web Design Request',$body, $header);
        if($send){ echo '<h3>Your messages was successfully sent....</h3>'; }
        else{ echo '<h3>There was a problem sending this message....</h3>'; }
        }
    else { foreach($errors as $error) { echo ("$error <br>"); } echo $form; }

    }
else { echo $form; }

?> 

Open in new window

0
Comment
Question by:BDC-Net
  • 2
4 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
Comment Utility
I may not be able to help you debug this, but I can offer a suggestion and an example of what might be a good design pattern.

Add these statements to the top of all of your PHP scripts:

ini_set('display_errors', TRUE);
error_reporting(E_ALL);

Here is my sample form-to-email script.

HTH, ~Ray
<?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";



// IF THE DATA HAS BEEN POSTED
if (!empty($_POST['email']))
{
    // DISABLED ON THE SERVER SIDE
    var_dump($_POST);
    die(' DISABLED');

    // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
    $email      = clean_string($_POST["email"]);
    $name       = clean_string($_POST["name"]);
    $telephone  = clean_string($_POST["telephone"]);

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

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


// A FORM TO TAKE CLIENT INPUT FOR THIS SCRIPT
$form = <<<ENDFORM
<form method="post">
Please enter your contact information
<br/>Email: <input name="email" />
<br/>Phone: <input name="telephone" />
<br/>Name:  <input name="name" />
<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 SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    return trim($str);
}

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
Comment Utility
PS: Since I leave this script on my server for a teaching example, I disabled it.  You should remove lines 22-25 as well as change the other information at the top to something that works for your needs.
0
 
LVL 30

Assisted Solution

by:Marco Gasi
Marco Gasi earned 125 total points
Comment Utility
I really don't find any evident problem with your code but some about security, not mail function. Don't trust any kind of input. These lines:

if(isset($_POST['name'])) { $name = $_POST['name']; } else { $name = ''; }
if(isset($_POST['email'])) { $email= $_POST['email']; } else { $email = ''; }
if(isset($_POST['phone'])) { $phone= $_POST['phone']; } else { $phone = ''; }
if(isset($_POST['message'])) { $message= $_POST['message']; } else { $message = 'Your message here'; }

represent a security issue since you don't filter data in any way, not you check if they are of the expected type. What about this: if a user typed malicious javascript code instead name and email?
You should always filter input using a whitelist or inspecting if it is as you expect it is: you can use ctype functions (http://it.php.net/manual/en/ref.ctype.php) or regular expression to be sure $_POST['email'] is really an email address.

Then you must escape output:

$name = htmlentities($name);
<input type='text' name='name' value='$name' />

htmlentities or strip_tags functions avoid some working code enter in your application

http://it.php.net/manual/en/function.htmlentities.php
http://it.php.net/strip_tags

I also suggest you read this book to learn about security issues:
http://phpsecurity.org/

Cheers
0
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 125 total points
Comment Utility
In PHP, '\r\n' only gets converted to CrLF when it is in double quoted strings.  This section works properly with double quotes but not with the single quotes you were using:

        $header = "From: " .$_POST['email'] ."\r\nContent-type: text/plain; charset=iso-8859-1\r\n";
        $body = 'Name:: '. $_POST['name'];
        $body .= "\nEmail:: ". $_POST['email'];
        $body .= "\nPhone:: ". $_POST['phone'];
        $body .= "\nMessage:: ". $_POST['message'];

Open in new window


Otherwise, you script appears to be work.  I would add a lot to it including better headers.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
This article discusses how to create an extensible mechanism for linked drop downs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now