0

I'm new to php and have been trying to figure out how to properly validate email addresses and that data has been entered into the text boxes. I can't really find what I need and trying to follow the examples on php.net sends me into a circle. Any help would be greatly appreciated! Also, am I even heading in the right direction with this form? The form works, I get an email formatted the way I want to either of the email address in the dropdown box.

-UPDATE- I rewrote some of my script...can someone check it out, I'm having more problems now. It will send an email even if nothing is entered into the form and even if you do it will send whatever you put. Example "email" test@example is being allowed through.

<?php

//Sainitize function
function sanitizeString($value){
$value = strip_tags($value);
$value = trim($value);
$value = escapeshellcmd($value);
$value = htmlentities($value);

return $value;
}

$send = $_POST[send];

//Email validation - does not work by the way
if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
$email_error = true;
$error_message[] = "Please use a valid email format: name@domain.com";
}     

if($send == 1){$email_sent = true; $step_1 = "complete";}
else{$email_sent = false; $step_1 = "complete";}

if($email_sent === true) {

$from = sanitizeString($_POST['from']);
$to = sanitizeString($_POST['to']);
$name = sanitizeString($_POST['name']);
$title = sanitizeString($_POST['title']);
$company = sanitizeString($_POST['company']);
$phone = sanitizeString($_POST['phone']);
$subject = sanitizeString($_POST['subject']);
$message = sanitizeString($_POST['message']);

// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $phoneErr = "";
$name = $address = $email = $message = $phone = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {

    $nameErr = "Please enter your name.";
}
else {
    $name = $_POST["name"];
}

if (empty($_POST["email"])) {
    $emailErr = "Please enter your email."; 
}
else {
    $email = $_POST["email"];
}
if (empty($_POST["phone"])) {
    $phoneErr = "Please enter a phone number.";
}
else {
    $phone = $_POST["phone"];
}
if (empty($_POST["message"]))  {
    $messageErr = "Cannot leave message box blank."; 
}
else {
    $message = $_POST["message"];
}

}

//select the correct to address
switch ($to) {
case "1":
$to = "contact1@example.com";
break;
case "2":
$to = "contact2@example.com";
break;
default:
$to = "contact1@example.com";
break;}

if($message_error !== true && $email_error !== true){
$email_headers = "From:".$from."\nMIME-Version: 1.0 \nContent-type: text/html; charset=iso-8859-1";

$message_send = "<h3>".$name."<br>".$title."<br>".$company."<br>".$phone."<br>".$from."</h3><hr><h4>".$subject."</h4>".$message;

if (mail($to, $subject, $message_send, $email_headers)) {$error_message = "Thank you, your email is on the way!";}
else {$error_message = "There seems to be a problem!";}}

}

?>
<body>

<form action="<?php ($_SERVER["PHP_SELF"]);?>" method="post">
<table style="border-collapse:collapse; border-spacing:0" >
<tr>
<td>Name:</td>
<td><input name="name" placeholder="Name*" type="text" class="text"/>
        <span class="error"><?php echo $nameErr;?></span></td>
</tr>
<tr>
<td>Title:</td>
<td><input type="text" placeholder="Title" name="title" size="50"/></td>
</tr>
<tr>
<td>Company:</td>
<td><input type="text" placeholder="Company" name="company" size="50" /></td>
</tr>
<tr>
<td>Phone:</td>
<td>
    <input name="phone" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo htmlspecialchars($phone);?>"/>
    <span class="style1">Example: 1234567890</span> <span class="error" style="color:#990000"><?php echo $phoneErr;?></span></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="from" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
    <span class="error"><?php echo $emailErr;?></span></td>
</tr>
<tr>
<td>To:</td>
<td><select name="to" size="1">
    <option value="1">Contact 1</option>
    <option value="2">Contact 2</option>
    </select></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" placeholder="Subject" size="50" /></td>
</tr>
<tr>
<td valign="top">Detail:</td>
<td colspan="2"><textarea cols="50" rows="4" name="message" placeholder="Type your message here."></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="hidden" name="send" value="1" /><input type="submit" value="Send" name="email_1" /></td>
</tr>

</table >
</form>
TAG
  • 68
  • 1
  • 8
  • possible duplicate of [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Beat Jan 12 '14 at 22:51
  • Well that tells me how to validate an email address so that it is example@example.com format and that helps. Although, how about validation with the other fields to make them required? – TAG Jan 13 '14 at 03:44
  • Ok I found a way to validate the input fields using, if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Please enter your name."; } else { $name = $_POST["name"]; } This is the name input field: Would this work with the above send script? – TAG Jan 13 '14 at 05:13
  • @Beat thanks, I was hoping to find something that alerted the user on the same form page that they left the email address field empty and not send an email through the form...which it does now for some reason. Really the people that will be using this form will be referenced by company name and then replied to either by phone or email if applicable. The email just creates a way to click on it when the email comes to the addressee. Thanks! – TAG Jan 16 '14 at 04:33

3 Answers3

0

For e-mail validation you can use filter_var function with FILTER_VALIDATE_EMAIL filter property. Here is nice article about input validation. Try this from php manual:

var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));

You can simplify your code, it's a bit messy. switch e-mail addresses is not very good practice. You can add values to form like this:

<select name="to" size="1">
    <option value="contact1@example.com">Contact1</option>
    <option value="contact2@example.com">Contact2</option>
</select>

You are also using deprecated function mysql_escape_string. ltrim and rtrim can be replaced with trim function.

UPDATE

There is still lot of mistakes in your code. Do you have displayed error reportings? Email switching is definitely not good solution for your problem. Take a look on the refactored code, it should work for you:

<?php

//Sainitize function
function sanitizeString($value)
{
    $value = strip_tags($value);
    $value = trim($value);
    $value = escapeshellcmd($value);
    $value = htmlentities($value);

    return $value;
}

$errorMessage = array();
$receivers = array(
    1 => 'contact1@example.com',
    2 => 'contact2@example.com'
);

if(isset($_POST['form']))
{
    $formData = $_POST['form'];

    if (filter_var($formData['from'], FILTER_VALIDATE_EMAIL)) {
        $from = sanitizeString($formData['from']);
    }
    else
    {
        $errorMessage[] = "Please use a valid email format: name@domain.com";
    }

    if(array_key_exists($formData['to'], $receivers))
    {
        $to = $receivers[$formData['to']];
    }
    else
    {
        $to = 'default@example.com';
    }

    if(strlen($formData['name']) > 0)
    {
        $name = sanitizeString($formData['name']);
    }
    else
    {
        $errorMessage[] = "Please enter your name.";
    }

    if(strlen($formData['title']) > 0)
    {
        $title = sanitizeString($formData['title']);
    }
    else
    {
        $title = '';
    }

    if(strlen($formData['company']) > 0)
    {
        $company = sanitizeString($formData['company']);
    }
    else
    {
        $company = '';
    }

    if(strlen($formData['phone']) > 0)
    {
        $phone = sanitizeString($formData['phone']);
    }
    else
    {
        $errorMessage[] = "Please enter a phone number.";
    }

    if(strlen($formData['subject']) > 0)
    {
        $subject = sanitizeString($formData['subject']);
    }
    else
    {
        $subject = '';
    }

    if(strlen($formData['message']) > 0)
    {
        $message = sanitizeString($formData['message']);
    }
    else
    {
        $errorMessage[] = 'Cannot leave message box blank.';
    }

    if (empty($errorMessage) && $formData['spam'] == 9)
    {
        $email_headers = "From:" . $from . "\nMIME-Version: 1.0 \nContent-type: text/html; charset=iso-8859-1";
        $message_send = "<h3>" . $name . "<br>" . $title . "<br>" . $company . "<br>" . $phone . "<br>" . $from . "</h3><hr><h4>" . $subject . "</h4>" . $message;

        if (mail($to, $subject, $message_send, $email_headers))
        {
            $errorMessage[] = 'Thank you, your email is on the way!';
        }
        else
        {
            $errorMessage[] = 'There seems to be a problem!';
        }
    }
}
?>
<body>

<?php if(!empty($errorMessage)): ?>
    <div style="border: 2px solid red">
        <ul>
            <?php foreach ($errorMessage as $error): ?>
                <li><?php echo $error; ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <table style="border-collapse:collapse; border-spacing:0">
        <tr>
            <td>Name:</td>
            <td>
                <input name="form[name]" placeholder="Name*" type="text" class="text" value="<?php echo isset($name) ? $name : ''; ?>"/>
            </td>
        </tr>
        <tr>
            <td>Title:</td>
            <td>
                <input type="text" placeholder="Title" name="form[title]" size="50" value="<?php echo isset($title) ? $title : ''; ?>"/>
            </td>
        </tr>
        <tr>
            <td>Company:</td>
            <td>
                <input type="text" placeholder="Company" name="form[company]" size="50" value="<?php echo isset($company) ? $company : ''; ?>"/>
            </td>
        </tr>
        <tr>
            <td>Phone:</td>
            <td>
                <input name="form[phone]" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo isset($phone) ? $phone : ''; ?>"/>
                <span class="style1">Example: 1234567890</span>
            </td>
        </tr>
        <tr>
            <td>Email:</td>
            <td>
                <input name="form[from]" placeholder="Email*" type="email" class="text" value="<?php echo isset($from) ? $from : ''; ?>">
            </td>
        </tr>
        <tr>
            <td>To:</td>
            <td>
                <select name="form[to]" size="1">
                    <option value="1">Contact 1</option>
                    <option value="2">Contact 2</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>Subject:</td>
            <td>
                <input type="text" name="form[subject]" placeholder="Subject" size="50" value="<?php echo isset($subject) ? $subject : ''; ?>"/>
            </td>
        </tr>
        <tr>
            <td valign="top">Detail:</td>
            <td colspan="2">
                <textarea cols="50" rows="4" name="form[message]" placeholder="Type your message here."><?php echo isset($message) ? $message : ''; ?></textarea>
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                3x3 = <input type="text" value="" name="form[spam]"/>
                <input type="submit" value="Send" />
            </td>
        </tr>
    </table>
</form>
Lukas Hajdu
  • 806
  • 7
  • 18
  • Oh I see on the select that I can declare the value within the option, that will help a great bit. Yeah I noticed that when I run some of my php scripts on xampp that I get deprecated errors I've been trying to make sure I get the right code in there. Like I said, I've been trying to teach myself php and while forums are great, some examples are out of date. :( – TAG Jan 13 '14 at 03:47
  • I ended up rewriting some of my script, can you have a look. I decided to still use the switch for the emails address because I have multiple address (different People/Departments) that the user can choose from and I don't want the address to be visible in the source/HTML. – TAG Jan 16 '14 at 04:25
  • Thank you so very much! It works perfectly. I will be able to add this to my site with no problems. I must say though that once I thought I was starting to pick PHP up and now I'm in the dark again. :( There seems to be so many ways to do something with it and so many examples out there. Books haven't helped either, that's where I got most of my reworked script... – TAG Jan 17 '14 at 20:29
  • Hello, I appreciate your help with this script a long time ago. I was wondering if you could help out again. I am trying to set the subject when the user selects from the contact drop down box. I really don't know array's that much yet so I'm not sure how to set $subject when the $to is set by your $receivers array. – TAG Jun 16 '14 at 19:14
0

I found this on php.net.. Does it work?

if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
   $email_error = true;
   $error_message[] = "Please use a valid email format: name@domain.com";
} 
Fabian
  • 107
  • 2
  • 2
  • 9
  • No, I tried it still sent off an email without validating the email field. – TAG Jan 13 '14 at 05:18
  • Thanks, I'm still having trouble preventing the form from sending an email regardless of what is put into any of the fields. – TAG Jan 16 '14 at 04:10
0

The Filter var does work. Try the following piece of code.

<?php
   $emailError = array();

   if(isset($_POST["send"])){

   $from = $_POST["from"];

   if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
   $emailError[] = "Please use a valid email format: name@domain.com\n\r";
   } 
   else {
    echo $from . " is a valid email.\n\r";
   }

   if ($emailError){
     foreach ($emailError as $key){
     echo $key;
     }
   }

} else {

?> 

  <form action="<?php ($_SERVER["PHP_SELF"]);?>" method="post">
  <table>
  <tr>
  <td>Email:</td>
  <td>
  <input name="from" placeholder="Email*" type="email" class="text" value="">
  </td>
  </tr>
  </table>
  <input type="submit" value="Send" name="send" />
  </form>

<?php
 }
?>
Fabian
  • 107
  • 2
  • 2
  • 9