• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 361
  • Last Modified:

PHP Emailer Script

hey Folks, I found this script and it seems to be what im looking for now im wondering  if someone could shed some light on how to sanitize data being input into it..
 
 <?php
//This is a very simple PHP script that outputs the name of each bit of information (that corresponds to the <code>name</code> attribute for that field) along with the value that was sent with it right in the browser window, and then sends it all to an email address (once you've added it to the script).

if (empty($_POST)) {
print "<p>No data was submitted.</p>";
print "</body></html>";
exit();
}

//Creates function that removes magic escaping, if it's been applied, from values and then removes extra newlines and returns to foil spammers. Thanks Larry Ullman!
function clear_user_input($value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
$value= str_replace( "\n", '', trim($value));
$value= str_replace( "\r", '', $value);
return $value;
}


if ($_POST['comments'] == 'Please share any comments you have here') $_POST['comments'] = '';	

//Create body of message by cleaning each field and then appending each name and value to it

$body ="Here is the data that was submitted:\n";

foreach ($_POST as $key => $value) {
$key = clear_user_input($key);
$value = clear_user_input($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
$body .= "$key: ";
$counter =1;
foreach ($_POST['extras'] as $value) {
//Add comma and space until last element
if (sizeof($_POST['extras']) == $counter) {
$body .= "$value\n";
break;}
else {
$body .= "$value, ";
$counter += 1;
}
}
} else {
$body .= "$key: $value\n";
}
} else {

$body .= "$key: $value\n";
}
}

extract($_POST);
//removes newlines and returns from $email and $name so they can't smuggle extra email addresses for spammers
$email = clear_user_input($email);
$name = clear_user_input($name);

//Create header that puts email in From box along with name in parentheses and sends bcc to alternate address
$from='From: '. $email . "(" . $name . ")" . "\r\n" . 'Bcc: yourmail@yourdomain.com' . "\r\n";


//Creates intelligible subject line that also shows me where it came from
$subject = 'Bed Order from Web Site';

//Sends mail to me, with elements created above
mail ('youremail@yourdomain.com', $subject, $body, $from);


?>

Open in new window

0
Eaddy Barnes
Asked:
Eaddy Barnes
2 Solutions
 
Ahmed MerghaniCommented:
Can you clarify your issue?
0
 
Marco GasiFreelancerCommented:
It looks like your values are sanitized yet. The only thing you could add, if that values were to be inserted in a database, is the use of mysql_real_escape_string() function:

function clear_user_input($value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
$value = mysql_real_escape_string($value);
$value= str_replace( "\n", '', trim($value));
$value= str_replace( "\r", '', $value);
return $value;
}

But this is not needed if you're only sending an email. With this function (which I would call clean_user_input), you're sanitizing inputs before to emailing them.

Perhaps you really have to clarify your question.

Cheers
0
 
Eaddy BarnesITAuthor Commented:
Oh, I'm wondering if it is secure enough to use without getting any email injections or other issues for a contact form on a site.
0
 
Ray PaseurCommented:
...secure enough to use without getting any email injections or other issues for a contact form on a site.
Nope.  You should do two things.  

First, add a CAPTCHA test to the script to be sure that you're only getting input from human beings.

Second, you should sanitize every input field. I use the functionality shown in this teaching example.
<?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

HTH, ~Ray
0
 
Marco GasiFreelancerCommented:
The most secure thing is to forbid html emails: prompt your user they can't use html in their messages and use strip_tags() (http://www.php.net/manual/en/function.strip-tags.php) to clean any html tag from a string:

function clear_user_input($value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
$value = mysql_real_escape_string($value);
$value= str_replace( "\n", '', trim($value));
$value= str_replace( "\r", '', $value);
$value= strip_tags($value);
return $value;
}

For spam you can use some script you find on the web: google for 'php no spam' and you'll find a lot. But remember the best and more secure way to avoid or at least to limit spam activities is to require your user to login: allowing only to authenticated users to write comments and messages  reduces a lot spam activities and I think is better than any anti-spam script you can find.

Hope this helps.

Cheers
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now