Jump to content


 


Register a free account to unlock additional features at BleepingComputer.com
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Click here to Register a free account now! or read our Welcome Guide to learn how to use this site.

Photo

PHP Email Form


  • Please log in to reply
5 replies to this topic

#1 birthdayfan

birthdayfan

  • Members
  • 2 posts
  • OFFLINE
  •  
  • Local time:04:41 PM

Posted 23 September 2012 - 03:58 PM

Hey, so I wanted to add a contact/email form on my website so I searched around the web and figured out how to do it in PHP.
I uploaded it to my server and when I went to it on my website, the screen was blank. Here's the code I added to my website:
<?php
$to = $person;
$subject = 'TRCC Mail';
$name = $_POST['name'];
$person = $_POST['person'];
$email = $_POST['email'];
$message = $_POST['mesage'];

$body = <<<EMAIL

$name($email) used the contact form.
He sent:
$message

EMAIL;
$header = "From: $email";
if(_POST)
{
if($name == "" || $email == "" || $message == "" || $person = "")
{
$feedback = 'Please fill out all the fields.";
}
else
{
mail($to , $subject, $body, $header);
$feedback = 'Message Sent.';
}

}
?>
<p id="feedback"><?php echo $feedback; ?></p>
                    <br />
                    <form action="?" method="post">
                      <ul>
                        <li> <label for="name">Name:</label> <input type="text"
                            name="name" id="name" /> </li>
                        <li> <label for="email">Your Email:</label> <input type="text"
                            name="email" id="email" /> </li>
                        <li>
                          <select name="person" id="person">
                            <option value="">Who would you like to contact?</option>
                            <option value="********@hotmail.com">Jacob
                              (Webmaster)</option>
                            <option value="*********@verizon.net">Jim
                              </option>
                            <option value="********@verizon.net">Kristin
                              </option>
                          </select>
                        </li>
                        <li> <label for="message">Message</label> <br />
                          <textarea id="message" name="message" cols="42" rows="9"></textarea>
                        </li>
                        <li> <input type="submit" value="Send" /> </li>
                      </ul>
                    </form>
I hope someone could shed light on what's wrong...

BC AdBot (Login to Remove)

 


#2 Grinler

Grinler

    Lawrence Abrams


  • Admin
  • 43,504 posts
  • ONLINE
  •  
  • Gender:Male
  • Location:USA
  • Local time:04:41 PM

Posted 24 September 2012 - 12:11 PM

Few mistakes here.

1. $person = $_POST['person']; must be initialized before $to. The way you ordered it, $to will be blank as $person is not initialized yet.

2. You forgot the $ in if($_POST). Not sure if that will even work. You can use something like this to check if the form was submitted:

if ($_SERVER['REQUEST_METHOD'] == "POST")

3. $person = "") should read $person == "")

4. $feedback = 'Please fill out all the fields."; You have the mismatched single quotes and double quotes around the string.

Finally, you need to add some sanitization to the person variable. You should make it so it checks for the legitimate email addresses and only sends to those. Otherwise people will use your form to send spam.

#3 birthdayfan

birthdayfan
  • Topic Starter

  • Members
  • 2 posts
  • OFFLINE
  •  
  • Local time:04:41 PM

Posted 24 September 2012 - 04:08 PM

Hey, so I applied the changes that you requested and it still shows as blank. I also tried to do it again with help from some tutorials. When I run it, it shows up but now, it doesn't send when you hit the send button, it just goes to a blank page. Here's the code:

<?php


$email_to = $_POST["person"];
$email_subject = 'TRCC Mail';


$required_fields = array('name','person','message');


$error_messages = array(
	'name' => 'Please enter a Name to proceed.',
	'email' => 'Please enter a valid Email Address to continue.',
	'message' => 'Please enter your Message to continue.'
);


$form_complete = FALSE;


$validation = array();


if(!empty($_POST)) {
	
	foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
	
	
	foreach($required_fields as $field) {		
		
		if(!array_key_exists($field, $_POST)) array_push($validation, $field);
		
		
		if($_POST[$field] == '') array_push($validation, $field);
		
		
		if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
	}
	
	
	if(count($validation) == 0) {
		
		$email_content = 'New Mesage: ' . "\n\n";
		
		
		foreach($_POST as $key => $value) {
			if($key != 'send') $email_content .= $key . ': ' . $value . "\n";
		}
		
		
		mail($email_to, $email_subject, $email_content);
		
	
		$form_complete = TRUE;
	}
}

function validate_email_address($email = FALSE) {
	return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}

function remove_email_injection($field = FALSE) {
   return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}

?>

<p></p>
                    <br />
                    <div id="formWrap">
                    <div id="form">.
                    <?php if($form_complete === FALSE): ?>
                    <form action="Contact.php" method="post" id="messages_form">
                      <div class="row">
                        <div class="label">Name: </div>
                        <div class="input">
                        <input type="text" id="name" class="detail" name="name" value="<?php echo isset($_POST['name'])? $_POST['name'] : ''; ?>" />
                        <?php if(in_array('name', $validation)): ?><span class="error"><?php echo $error_messages['name']; ?></span><?php endif; ?>
                        </div>
                        <div class="context">ie. Joe Smith or Jane Doe.</div>
                    	</div>
                        
                        <div class="row">
                        <div class="label">Email: </div>
                        <div class="input">
                        <input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
                        <?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
                        </div>
                        <div class="context">We will not share your email with any third party vendors and we will not spam you.</div>
                    	</div>
                        <br />
                        <select name="person" id="person">
                        <option>Who would you like to contact?</option>
                        <option value="emailwithheld@hotmail.com">Jacob(Webmaster)</option>
                       <option value="emailwithheld@verizon.net">Jim</option>
                       </select> 
                      <div class="row">
                        <div class="label">Message: </div>
                        <div class="input">
                        <textarea id="message" name="message" class="message"><?php echo isset($_POST['message'])? $_POST['message'] : ''; ?></textarea>
                        <?php if(in_array('message', $validation)): ?><span class="error"><?php echo $error_messages['message']; ?></span><?php endif; ?>
                        </div>
                    	</div>
                        
                        <div class="submit">
                        <input type="submit" id="send" name="send" value="Send" />
                        </div>
                        </form>
                        <?php else: ?>
<p>Thank you for your Message!</p>
<?php endif; ?>
                        
                    </div>
                    </div>
Should I continue on with this code or work on the other one and again, I hope someone can shed light on what's wrong...

#4 Grinler

Grinler

    Lawrence Abrams


  • Admin
  • 43,504 posts
  • ONLINE
  •  
  • Gender:Male
  • Location:USA
  • Local time:04:41 PM

Posted 25 September 2012 - 07:43 AM

Works for me. If you are specifying the name of the php script that will process the form, make sure its the name you specified. In this case Contact.php. You can leave it blank to specify the same form:

<form action="" method="post" id="messages_form">

You still have the issue where your form can easily be used for spam. When I said to sanitize your input, I meant to make it so that the possible email addresses you can send to are hard coded in the php. There is no need for reg exp in this code.

Instead create an array of all the possible email address that the visitor can accept.

$pos_recip = array('asd@example.com', 'bob@example.com', 'susan@example.com');

Test the email address selected in the form against this array and if the user is not a valid one that you want mail sent to, change it to a default email. If you use this method, you can remove the two regexp checks. If you wish, instead of default to a particular use, you can have it display an error instead.

Something like:


$email_to = trim(strtolower($_POST['person']));

$pos_recip = array('asd@example.com', 'bob@example.com', 'susan@example.com');

// Check if $_POST['person'] is a valid recipient. If its not send the email to a default user.

if(!in_array($email_to, $pos_recip))
  $email_to = 'bob@example.com';

mail($email_to, $email_subject, $email_content);

You are also modifying contents of the $_POST variable which is probably not the best method in the event you need access to its original data in the future. Instead you should create a different variable to store the returned data.

Edited by Grinler, 26 September 2012 - 08:29 AM.
mistakenly changed name of variable


#5 KamakaZ

KamakaZ

  • Members
  • 739 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Victoria
  • Local time:07:41 AM

Posted 25 September 2012 - 06:18 PM

In the example above, the variable name is changed between $email_to and $to_email. Even though it was checking the array, the variable set initially and the variable passed through to the mail function were never modified so would still mail whoever you initially passed in $_POST['person']


$email_to = trim(strtolower($_POST['person']));

$pos_recip = array('asd@example.com', 'bob@example.com', 'susan@example.com');

// Check if $_POST['person'] is a valid recipient. If its not send the email to a default user.

/*
  // PREVIOUS TO CODE CHANGE
if(!in_array($to_email, $pos_recip))
  $to_email = 'bob@example.com';
*/

if(!in_array($email_to, $pos_recip))
  $email_to = 'bob@example.com';

mail($email_to, $email_subject, $email_content);

There's no place like 127.0.0.1
There are 10 types of people in the world, those that can read binary, and those who can't.


#6 Grinler

Grinler

    Lawrence Abrams


  • Admin
  • 43,504 posts
  • ONLINE
  •  
  • Gender:Male
  • Location:USA
  • Local time:04:41 PM

Posted 26 September 2012 - 08:28 AM

That was my mistake. Variable was not meant to change. I have updated my original code.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users