This should be easy???

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
skubeedoo
Forum Newbie
Posts: 7
Joined: Wed Jun 17, 2009 12:05 pm

This should be easy???

Post by skubeedoo »

I'm a total nube and can really use some help. I've made a website in dreamweaver with a simple form that visitors can request a demo. they enter thier name and email and push send. The visitor will recieve an email with a link to the demo. What I'd like to have happen is the visitor receives the email and their informaiton (name and email) is submitted to a database for a record. I look at formmail, but I didn't see how to send data to the db. Any help would be greatly appreciated. :D
skubeedoo
Forum Newbie
Posts: 7
Joined: Wed Jun 17, 2009 12:05 pm

Re: This should be easy???

Post by skubeedoo »

I found a script from http://www.mindpalette.com called processform 3.0 and it looks like this would do the job. As I mentioned, I'm REALLY new to this and I'm sure this will be frustrating and will probably be making more inquiries as I go along.
skubeedoo
Forum Newbie
Posts: 7
Joined: Wed Jun 17, 2009 12:05 pm

Re: This should be easy???

Post by skubeedoo »

Moderator has enclosed the code in

Code: Select all

 ... [/php ] tags. In the future, please do that yourself when you post code here.[/color]
I uploaded a "test php mail" script to see if the server would send an email and it didn't. I'm hosting through go daddy and they said the email should go through relay:hosting.secureserver.net 
Any suggestions? Here's the code of the test:
[syntax=php] 
<?php
// Test PHP Email script by Nate Baldwin, http://www.mindpalette.com
unset($email);
unset($message);
$errors = "";
$formStatus = (isset($HTTP_POST_VARS['formStatus'])) ? $HTTP_POST_VARS['formStatus'] : "";
if ($formStatus == "submitted") {
    $email = (isset($HTTP_POST_VARS['email'])) ? $HTTP_POST_VARS['email'] : "";
    if ($email == "") $errors .= "Please enter your email address before submitting form.<br>\n";
    $emailPattern = "^[A-Z0-9._-]+@[A-Z0-9._-]+\.[A-Z]{2,4}$";
    if ($email != "" AND !eregi($emailPattern, $email)) 
        $errors .= "The email address entered does not to be a valid address for testing.<br>\n";
    if ($errors == "") {
        $subject = "PHP Email Test";
        $message = "If you receive this email, your server has successfully sent an email using PHP.\n";
        @$mailStatus = mail($email, $subject, $message);
        if (!$mailStatus) $errors .= "Server error - PHP has not been configured to send out emails yet, sorry.<br>\n";
        }
    }
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 
<html>
 
    <head>
        <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
        <meta name="generator" content="Adobe GoLive">
        <title>Test PHP Email Configuration</title>
        <style type="text/css" media="screen"><!--
body, div, td, p  { color: black; font-size: 13px; font-family: Verdana, Arial, Helvetica, sans-serif; background-color: #c8c8c8 }
a { color: #00417d; font-size: 13px; font-family: Verdana, Arial, Helvetica, sans-serif; text-decoration: none }
a:link { color: #00417d; font-size: 13px; font-family: Verdana, Arial, Helvetica, sans-serif; text-decoration: none }
a:visited { color: #00417d; font-size: 13px; font-family: Verdana, Arial, Helvetica, sans-serif; text-decoration: none }
a:hover { color: #0064ff; font-size: 13px; font-family: Verdana, Arial, Helvetica, sans-serif; text-decoration: underline }
.error { color: #c80019 }
.success { color: #00417d }
h1   { color: #00417d; font-size: 32px; font-family: "Times New Roman", Georgia, Times; font-weight: normal }
strong { font-size: 16px; font-weight: bold }
form { margin: 0; padding: 6px 0 }
--></style>
    </head>
 
    <body bgcolor="#ffffff">
        <div align="center">
            <h1>Test PHP Email</h1>
            <p>To test your server's PHP email configuration, enter your valid<br>
                email address below and hit the "test now" button.</p>
            <hr width="75%">
            <form id="FormName" action="#" method="post" name="FormName">
                your email address:&nbsp;<input type="text" name="email" size="32">&nbsp;<input type="hidden" name="formStatus" value="submitted"><input type="submit" name="submitButtonName" value="test now">
            </form>
<?php
if ($formStatus == "submitted") {
    if ($errors != "") {
        print("
            <hr width=\"75%\">
            <span class=\"error\"><strong>ERROR:</strong><br>
            $errors</span><br>
            &nbsp;<br>
            ");
        } else {
        print("
            <hr width=\"75%\">
            <span class=\"success\"><strong>Success!</strong><br>
            Email message has been sent.<br>
            If you do not receive your email, try a different address.<br>
            If still no luck, your server's outgoing email may not be working right.<br>
            &nbsp;</span>
            ");
        }
    }
?><br>
            &nbsp;<br>
            &nbsp;<br>
            &nbsp;<a href="http://www.mindpalette.com">www.mindpalette.com</a><br>
            &nbsp;</div>
    </body>
</html>[/syntax]
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: This should be easy???

Post by califdon »

To help yourself get help, learn to provide enough information so that someone can help you. Instead of saying just "it didn't work", tell us exactly what happened. Did you get an error message? If so, exactly what was the error message? Did you even get the form to appear? These are the kinds of things that programmers use to determine what went wrong. When you don't tell us, it's impossible to help you and most people will just not waste any more of their time reading your post.
skubeedoo
Forum Newbie
Posts: 7
Joined: Wed Jun 17, 2009 12:05 pm

Re: This should be easy???

Post by skubeedoo »

Sorry. When the address is entered and the submit button is pushed, nothing happens. No error messages, nothing. No email is sent. I used several email addresses, and so did go daddy...nothing happens. They said the PHP is already enabled on the hosting side.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: This should be easy???

Post by califdon »

OK, that just means that there's an error in the code, it probably has nothing to do with the email part. That's a very awkward and very old code snippet. I realize that you have no way to judge that, yourself, but it is. I don't even want to try to debug it.

Try this: put the following in a file named mailtest.php and upload it to godaddy. Then go to your browser and address your domain/mailtest.php. It should send you an email. Oh, of course, change YOUREMAILADDY to whatever your email address is.

Code: Select all

<?php
ini_set("display_errors","2");
ERROR_REPORTING(E_ALL);
$to="YOUREMAILADDY";
$subj="Test Email";
$from="FROM: myself@godaddy.com";
$body="This is a test email from my domain at GoDaddy.com";
mail($to, $subj, $body, $from) or die("the mail failed");
echo "the mail was sent.";
?>
If you want to copy-and-paste from the above, turn off the line numbers by clicking where it says Line Number On/Off.
skubeedoo
Forum Newbie
Posts: 7
Joined: Wed Jun 17, 2009 12:05 pm

Re: This should be easy???

Post by skubeedoo »

Thank you califdon. If the code is old, then there's a chance the app that I'm thinking about using is old as well. What I'm trying to accomplish seems very simple. I'm looking for a way to have a form on my site that lets visitors receive an email that gives them a link to a demo. The form will have three pieces of info: name, company and email. What i want to have happen is when they push submit, they get an email with the link and the three pieces of info are written to a simple mySql database. Is there something out there that will do this? All of the formmail scripts I've seen don't write to a db.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: This should be easy???

Post by califdon »

skubeedoo wrote:Thank you califdon. If the code is old, then there's a chance the app that I'm thinking about using is old as well. What I'm trying to accomplish seems very simple. I'm looking for a way to have a form on my site that lets visitors receive an email that gives them a link to a demo. The form will have three pieces of info: name, company and email. What i want to have happen is when they push submit, they get an email with the link and the three pieces of info are written to a simple mySql database. Is there something out there that will do this? All of the formmail scripts I've seen don't write to a db.
That's because sending an email and working with a database are completely different kinds of tasks. If you're seeking help on one of those, you're unlikely to find help for the other in the same place.

Yes, it's pretty straightforward to do that, but everybody will have their own requirements, so this is why you learn to program with PHP, so you can do specifically what you need to do. The only advice I can give you is to learn some basic PHP and MySQL programming. Either that or find somebody who is willing to write an application for you, which I would think is rather unlikely.
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: This should be easy???

Post by Eric! »

The reason nothing happens is because line 51 is not right. You have to tell html where to post the results upon submit. I don't recall the exact syntax for reposting to self, but I'm sure you can google that. I'm pushed for time right now.

Another HUGE problem is the spamers are going to have a heyday with your new script by injecting all kinds of nasty stuff into your mail variables. You have to include heavy filtering for any input fields that pipe through mail().

Lastly, there is a non-obvious problem with mail() where if you don't use a special tag in the 4th (yes 4th field, see manual) the reply-to address won't get set and many spam filters will filter out your messages.

Adding in the mysql database stuff is pretty easy once you get it configured. PHP and mysql work well together.

When I get some time I'll post some code. One other thing you should do is log the IPs of people using your form. It is a good way to stop abuse in the long term.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: This should be easy???

Post by califdon »

Eric! wrote:The reason nothing happens is because line 51 is not right. You have to tell html where to post the results upon submit. I don't recall the exact syntax for reposting to self, but I'm sure you can google that.
Actually, that's not true. Using just a hash sign (#), or even leaving it blank, will post the results to the same document, at least with the normal configuration of Apache. I think it's not good practice to do it that way, but it's done a lot and it does work.
Another HUGE problem is the spamers are going to have a heyday with your new script by injecting all kinds of nasty stuff into your mail variables. You have to include heavy filtering for any input fields that pipe through mail().
That's for sure.
Adding in the mysql database stuff is pretty easy once you get it configured. PHP and mysql work well together.
While that's a fair statement for someone who has some knowledge of, and experience with HTML, PHP, MySQL and maybe Javascript, I would say that from the nature of this question, it's definitely NOT going to be "pretty easy" for this person.
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: This should be easy???

Post by Eric! »

[Note to moderator, maybe the subject of this thread should be changed to something more descriptive]

I still think line 51 is the problem, but I don't post data to the same page normally and I don't feel like looking into it.

Anyway here is how I would do it based on many battles with spammers. Have an entry html page with the form. I appologize in advance form my form example. I am posting from a device with no web tools so there is a table or two in there that needs to be cleaned up.
contact.html:

Code: Select all

<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><meta http-equiv="Content-Language" content="en-us"><title>Contact Us</title><meta name="description" content="Use this form to send an email message."></head> <body "bgcolor="#FFFFFF" text="#000000" link="#993333" vlink="#333399" alink="#006633"><font face="trebuchet ms,arial,helvetica"> <SCRIPT TYPE="text/javascript"><!-- hide script from old browsersfunction TestDataCheck(){    // extract data from the form and test it    // before sending it to the php script for email    var username = document.feedback.Username.value;    var useremail = document.feedback.UserEmail.value;    var subject = document.feedback.Subject.value;    var msg=document.feedback.Comments.value;    var returnval = true; //  msg.replace=("'","|");  //can add some prefiltering like this//  msg.replace=("\"","^");//  document.feedback.Comments.value=msg; //update filtered text     if (username.length<4)     {       alert("Please Enter Your Name.");       returnval = false;    }     if (useremail.length<5)     {       alert("Please Enter Your Email Address.");       returnval = false;    }     if (subject.length<2)     {       alert("Please Enter a Subject.");       returnval = false;    }     return returnval;}// end script --></SCRIPT> <div align="center">  <center></font>  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" width="600">  <tr>    <td valign="top" width="142" style="border-left-style:none; border-left-width:medium; border-right-style:solid; border-right-width:1; border-top-style:none; border-top-width:medium; border-bottom-style:none; border-bottom-width:medium"><!--mstheme--><font face="trebuchet ms,arial,helvetica">    <p>&nbsp;</p>    </font></td>    <td valign="top" width="5" style="border-right-style:none; border-right-width:medium; border-top-style:none; border-top-width:medium; border-bottom-style:none; border-bottom-width:medium"><!--mstheme--><font face="trebuchet ms,arial,helvetica"><!--mstheme--></font></td>    <td valign="top" height="100%" style="border-right-style:none; border-right-width:medium; border-top-style:none; border-top-width:medium; border-bottom-style:none; border-bottom-width:medium" width="452"><!--mstheme--><font face="trebuchet ms,arial,helvetica">    <p>Contact us by leaving a message and we'll get back to you as soon     as possible.</p>    <form name="feedback" action="_mail.php" method="POST" onSubmit="return TestDataCheck()" >      <p><strong>All information is kept        strictly private:</strong></p>        </font><table id="table1">            <tr>                <td><font face="trebuchet ms,arial,helvetica">Your Name:</font></td>                <td><font face="trebuchet ms,arial,helvetica">                <input type="text" size="35" maxlength="50" name="Username"></font></td>            </tr>            <tr>                <td><font face="trebuchet ms,arial,helvetica">Your Email: </font></td>                <td><font face="trebuchet ms,arial,helvetica">                <input type="text" size="35" maxlength="150" name="UserEmail"></font></td>            </tr>        </table>        <table id="table2">            <tr>                <td width="60"><font face="trebuchet ms,arial,helvetica">Subject:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font></td>                <td><font face="trebuchet ms,arial,helvetica">                <input type="text" size="35" maxlength="150" name="Subject"></font></td>            </tr>            </table><font face="trebuchet ms,arial,helvetica">      <p><strong>Enter your message in the space provided below:</strong></p>      <dl>        <dd>        <textarea name="Comments" rows="5" cols="42" style="text-align: left; line-height: 100%" maxlength="1000"></textarea></dd>        <dd>&nbsp;</dd>      </dl>      <p align="center">      <input type=SUBMIT value="Send Message">      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      <input type="RESET"></p>    </form>    </font></td>  </tr></table></body></html>
ok, that is the form. note the simple checking of the fields with a little javascript. Since anyone can see this don't put a lot of time in filtering here. This can all be bypassed by a spammer anyway. The other thing you see is the data is sent to _mail.php.
_mail.php:

Code: Select all

<?php 
//Blocked IP Addresses
//Put IPs in here of addresses that try to insert spam
//The ips in this array are just examples (i did get spam attempts
//from them) but you should remove them and start fresh.
$blockedip=array("130.76.32.16","98.203.163.91","130.76.32.23"
                ,"77.87.152.62","77.92.88.9","89.76.164.52");
 
function InjectionAttempt($input) // this removes any injection characters
{
    if (eregi("%0a", $input) ||
    eregi("%0d", $input) ||
    eregi("Content-Type:", $input) ||
    eregi("bcc:", $input) ||
    eregi("to:", $input) ||
    eregi("cc:", $input)) 
    {
        return 1;  // bastards
    } 
    else 
    {
        return 0;
    }
}
 
function InjectionAttempt2($input) // use this for fields that contain return codes and line feeds
{
    if (eregi("Content-Type:", $input) ||
    eregi("bcc:", $input) ||
    eregi("to:", $input) ||
    eregi("cc:", $input)) 
    {
        return 1;  // bastards
    } 
    else 
    {
        return 0;
    }
}
 
function errormsg()
{
    printf("<br><br>Sorry, the system failed to send message.  Please avoid using the following in your entries:<br>to:<br>bcc:<br>cc:<br>or other non-ASCII characters<br><br>Press the back button and edit your message.");
    return;
}
 
function errormsg2()
{
    printf("<br><br>Sorry, the system failed to send message.  Please avoid using links in your message or other non-ASCII characters<br><br>Press the back button and edit your message.");
    return;
}
 
function stripjunk($sting,&$cnt) //change potential hacked user input fields like a bee
{
    //This routine is very agressive and will alter innocent
    //messages, but the meaning won't be lost
    //$cnt returns a count of the number of the most suspicious characters
    //you can modify this filter to suit your needs
    for($i=0; $i<strlen($sting); $i+=1) //I used an old fashioned technique for clarity 
    {
        if($sting[$i]==':') {$sting[$i]='-'; $cnt++;} // only count characters that could be in links
        if($sting[$i]=='<') {$sting[$i]='.';}
        if($sting[$i]=='>') {$sting[$i]='.';}
        if($sting[$i]=='[') {$sting[$i]='.';}
        if($sting[$i]==']') {$sting[$i]='.';}
        if($sting[$i]=='{') {$sting[$i]='.';}
        if($sting[$i]=='}') {$sting[$i]='.';}
        if($sting[$i]==';') {$sting[$i]='.';}
        if($sting[$i]=='*') {$sting[$i]='.';}
        if($sting[$i]=='/') {$sting[$i]='.'; $cnt++;} // could be a link http://spam.com
        if($sting[$i]=='\\') {$sting[$i]='.';}
        if($sting[$i]=='%') {$sting[$i]='.';} 
    }
    return $sting;
}
 
if(isset($_POST["Username"]) && isset($_POST["UserEmail"]))
{
  // Incoming input: Username,UserEmail,Comments,Subject
  // You can remove the printf and not post an error message just to keep them guessing
  // You could also sanatize the fields and send the message to yourself for analysis, but be careful!
  // You could save to a log file (safest) for a record and the track down the spammer later
    if(InjectionAttempt($_POST["Username"]) ) {printf ("Problem with Name Field<br>%s",$_POST["Username"]); errormsg(); return;}
    if(InjectionAttempt($_POST["UserEmail"]) ) {printf ("Problem with your Email Field<br>",$_POST["UserEmail"]); errormsg(); return;}
    if(InjectionAttempt2($_POST["Comments"]) ) {printf ("Problem with Comments<br>",$_POST["Comments"]); errormsg(); return;}
    if(InjectionAttempt($_POST["Subject"]) ) {printf ("Problem with the Subject field<br>",$_POST["Subject"]); errormsg(); return;}
 
    //loop through IP list to block
    //if you don't post error messages or redirect spam attempts
    //you can add persistant spammers or abusers to the blocked list
    //be careful because you can also block legit people sharing the ip
    $block=0;
    foreach($blockedip as $hit)
    {
        if(strcmp($_SERVER['REMOTE_ADDR'],$hit)==0) $block=1;
        // Since this could be a valid message, just tag it, but send
        // the message with the blocked ip notice.  If needed, you could put
        // some code in here to redirect this user to a html page
        // that tells them due to abuse they are blocked...
    }
 
                    $spam_cnt=0; // count the number of insertions detected in function stripjunk
                    $username=stripjunk($_POST["Username"],$spam_cnt);
                    $useremail=stripjunk($_POST["UserEmail"],$spam_cnt);
                    $comments=stripjunk($_POST["Comments"],$spam_cnt);
 
                    $subject = "Feedback: ".stripjunk($_POST["Subject"],$spam_cnt);
 
                // To avoid users inserting really long strings, make the truncated
                // you can also limit them in the html input form
                    if(strlen($username)>40) $username=substr($username,0,40); // truncate strings
                    if(strlen($useremail)>150) $useremail=substr($useremail,0,150);
                    if(strlen($subject)>150) $subject=substr($subject,0,150);
                    if(strlen($comments)>1000) $comments=substr($comments,0,1000);
 
                  //build the message to yourself
                    $content = "\nNAME:\n".$username;
                    $content .= "\n\nEmail:\n".$useremail;
                    $content .= "\n\nMESSAGE:\n".$comments;
                    $content .= "\n\nSent:\n".date("l dS F Y h:i:s A")." PST";
                    $content .= "\nSent from: ".$_SERVER['REMOTE_ADDR'];
                    if($block) $content .= "\nIP BLOCKED\n";
 
                    //Build the email header            
                    $from="you@domian.com";  //this is really from your site to you
                    $from_name = "First Last";  // Plain Text Name for Email Address
            $eol="\r\n";    
            $headers = "Reply-To: ".$from_name."<".$from.">".$eol;
            $headers.= "From: ".$from_name."<".$from.">".$eol;
            $headers.= "Content-type:   text/plain".$eol;
            $headers.= "Message-ID: <".time()."-".$from.">".$eol;
            //There are tons of sites about email headers and mime formats, but this seems to work
 
                    if($spam_cnt>5)
                    {
                        //probably spam, several hits occurred when calling stripjunk
                        //I usually email these messages anyway because their message
                        //is sanatized.  This way I can track the IP and see if they
                        //are trying anything new.
                        //However this example rejects them                 
                        if(stristr($comments,"http")!=FALSE) // does http appear in the text?
                        {
                            errormsg2();  // this is for sure spam attempt  reject.
                            return;
                        }
                    }
 
            // SEND THE EMAIL
            $to="you@your.domain";
            ini_set(sendmail_from,$from);  // the INI lines are to force the From Address to be used !  
            $returnpath="-f ".$from;  // Forces the return path to be configured properly   
          $mail_sent = mail($to, $subject, $content, $headers, $returnpath);
            //Note I don't do any error checking on $mail_sent because mail() often produces strange return codes yet works
 
            //Tell them they are blocked (even though you allowed
            //the message through) to discourage future attempts
                    if ($block==0) header('Location: http://www.example.com/_thankyou.htm');
                    else header('Location: http://www.example.com/_block.htm');                 
}   
?>
Ok, this is where all the work is done. Read the comments, modify it to your system, and try it. I appologize again if there are any typos because I can't test it on this device.

This php script formats the form data and sends it to you. I know you need something different but I think this code is generic enough to jump start you. By the way his script is very agressive against spammers and is definately overkill.

Let me know how it goes and if you find any errors/problems. Then we can move on to the database if you want. However, I'm thinking maybe it would be easier for you just to keep copies of the outgoing messages as a record. It isn't like you are recording sales or have a members login where this information gets used over and over.

Edit: I just realized some extra field checks were dropped during the cut/paste action. They aren't critical for now but I'll post the complete thing later. Gotta go SEE THE _MAIL.PHP posted below for an additional filter to check for vaild email addresses (not critical, but helpful)
Last edited by Eric! on Tue Jun 23, 2009 11:51 am, edited 1 time in total.
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: This should be easy???

Post by Eric! »

The piece that was missing is just a check on the email address to see if it is valid. I find this isn't a common problem because giving a 'valid' fake email is easy. While looking into the subject again I came across a great function is_email() from http://blog.dominicsayers.com/2009/01/2 ... validator/

So if you want to download that function and tack it on, I put a section in the code to call it, just uncomment it. For most though it is overkill.

here is _mail.php again with a short email address check. See lines 94-111 and function errormsg3.

Code: Select all

<?php 
//Blocked IP Addresses
//Put IPs in here of addresses that try to insert spam
//The ips in this array are just examples (i did get spam attempts
//from them) but you should remove them and start fresh.
$blockedip=array("130.76.32.16","98.203.163.91","130.76.32.23"
                ,"77.87.152.62","77.92.88.9","89.76.164.52");
 
function InjectionAttempt($input) // this removes any injection characters
{
    if (eregi("%0a", $input) ||
    eregi("%0d", $input) ||
    eregi("Content-Type:", $input) ||
    eregi("bcc:", $input) ||
    eregi("to:", $input) ||
    eregi("cc:", $input)) 
    {
        return 1;  // bastards
    } 
    else 
    {
        return 0;
    }
}
 
function InjectionAttempt2($input) // use this for fields that contain return codes and line feeds
{
    if (eregi("Content-Type:", $input) ||
    eregi("bcc:", $input) ||
    eregi("to:", $input) ||
    eregi("cc:", $input)) 
    {
        return 1;  // bastards
    } 
    else 
    {
        return 0;
    }
}
 
function errormsg() //someone tried to inject data into mail()
{
    printf("<br><br>Sorry, the system failed to send message.  Please avoid using the following in your entries:<br>to:<br>bcc:<br>cc:<br>or other non-ASCII characters<br><br>Press the back button and edit your message.");
    return;
}
 
function errormsg2() //someone tried to send a link
{
    printf("<br><br>Sorry, the system failed to send message.  Please avoid using links in your message or other non-ASCII characters<br><br>Press the back button and edit your message.");
    return;
}
 
function errormsg3() // bad email address
{
    printf("<br><br>Sorry, your email address is not valid.<br><br>Press the back button and edit your message.");
}
 
function stripjunk($sting,&$cnt) //change potential hacked user input fields like a bee
{
    //This routine is very agressive and will alter innocent
    //messages, but the meaning won't be lost
    //$cnt returns a count of the number of the most suspicious characters
    //you can modify this filter to suit your needs
    for($i=0; $i<strlen($sting); $i+=1) //I used an old fashioned technique for clarity 
    {
        if($sting[$i]==':') {$sting[$i]='-'; $cnt++;} // only count characters that could be in links
        if($sting[$i]=='<') {$sting[$i]='.';}
        if($sting[$i]=='>') {$sting[$i]='.';}
        if($sting[$i]=='[') {$sting[$i]='.';}
        if($sting[$i]==']') {$sting[$i]='.';}
        if($sting[$i]=='{') {$sting[$i]='.';}
        if($sting[$i]=='}') {$sting[$i]='.';}
        if($sting[$i]==';') {$sting[$i]='.';}
        if($sting[$i]=='*') {$sting[$i]='.';}
        if($sting[$i]=='/') {$sting[$i]='.'; $cnt++;} // could be a link http://spam.com
        if($sting[$i]=='\\') {$sting[$i]='.';}
        if($sting[$i]=='%') {$sting[$i]='.';} 
    }
    return $sting;
}
 
//Check to see if two key fields contain data and bail out if blank
if(isset($_POST["Username"]) && isset($_POST["UserEmail"]))
{
  // Incoming input: Username,UserEmail,Comments,Subject
  // You can remove the printf and not post an error message just to keep them guessing
  // You could also sanatize the fields and send the message to yourself for analysis, but be careful!
  // You could save to a log file (safest) for a record and the track down the spammer later
    if(InjectionAttempt($_POST["Username"]) ) {printf ("Problem with Name Field<br>%s",$_POST["Username"]); errormsg(); return;}
    if(InjectionAttempt($_POST["UserEmail"]) ) {printf ("Problem with your Email Field<br>",$_POST["UserEmail"]); errormsg(); return;}
    if(InjectionAttempt2($_POST["Comments"]) ) {printf ("Problem with Comments<br>",$_POST["Comments"]); errormsg(); return;}
    if(InjectionAttempt($_POST["Subject"]) ) {printf ("Problem with the Subject field<br>",$_POST["Subject"]); errormsg(); return;}
 
  //There is a really good email validation function
  //at http://blog.dominicsayers.com/2009/01/2 ... validator/
  //and if you include that function uncomment the following to use it
  /*
  //Validate email address with dns checking off
  //turn on dns checking if your host allows and you want it
  if(!is_email($_POST["UserEmail"],0) {errormsg3(); return;}
  */
  
  //  If you don't want to do massive checking with the is_email
  //    function, just do the following to simply check field sizes
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $_POST["UserEmail"])) 
  {
    // Email invalid because wrong number of characters 
    // in one section or wrong number of @ symbols.
    errormsg3(); 
    return;
  }
 
    //loop through IP list to block
    //if you don't post error messages or redirect spam attempts
    //you can add persistant spammers or abusers to the blocked list
    //be careful because you can also block legit people sharing the ip
    $block=0;
    foreach($blockedip as $hit)
    {
        if(strcmp($_SERVER['REMOTE_ADDR'],$hit)==0) $block=1;
        // Since this could be a valid message, just tag it, but send
        // the message with the blocked ip notice.  If needed, you could put
        // some code in here to redirect this user to a html page
        // that tells them due to abuse they are blocked...
    }
 
                    $spam_cnt=0; // count the number of insertions detected in function stripjunk
                    $username=stripjunk($_POST["Username"],$spam_cnt);
                    $useremail=stripjunk($_POST["UserEmail"],$spam_cnt);
                    $comments=stripjunk($_POST["Comments"],$spam_cnt);
 
                    $subject = "Feedback: ".stripjunk($_POST["Subject"],$spam_cnt);
 
                // To avoid users inserting really long strings, make the truncated
                // you can also limit them in the html input form
                    if(strlen($username)>40) $username=substr($username,0,40); // truncate strings
                    if(strlen($useremail)>150) $useremail=substr($useremail,0,150);
                    if(strlen($subject)>150) $subject=substr($subject,0,150);
                    if(strlen($comments)>1000) $comments=substr($comments,0,1000);
 
                  //build the message to yourself
                    $content = "\nNAME:\n".$username;
                    $content .= "\n\nEmail:\n".$useremail;
                    $content .= "\n\nMESSAGE:\n".$comments;
                    $content .= "\n\nSent:\n".date("l dS F Y h:i:s A")." PST";
                    $content .= "\nSent from: ".$_SERVER['REMOTE_ADDR'];
                    if($block) $content .= "\nIP BLOCKED\n";
 
                    //Build the email header            
                    $from="you@domian.com";  //this is really from your site to you
                    $from_name = "First Last";  // Plain Text Name for Email Address
        $eol="\r\n";    
        $headers = "Reply-To: ".$from_name."<".$from.">".$eol;
        $headers.= "From: ".$from_name."<".$from.">".$eol;
        $headers.= "Content-type:   text/plain".$eol;
        $headers.= "Message-ID: <".time()."-".$from.">".$eol;
        //There are tons of sites about email headers and mime formats, but this seems to work
 
                    if($spam_cnt>5)
                    {
                        //probably spam, several hits occurred when calling stripjunk
                        //I usually email these messages anyway because their message
                        //is sanatized.  This way I can track the IP and see if they
                        //are trying anything new.
                        //However this example rejects them                 
                        if(stristr($comments,"http")!=FALSE) // does http appear in the text?
                        {
                            errormsg2();  // this is for sure spam attempt  reject.
                            return;
                        }
                    }
 
        // SEND THE EMAIL
        $to="you@your.domain";
        ini_set(sendmail_from,$from);  // the INI lines are to force the From Address to be used !  
        $returnpath="-f ".$from;  // Forces the return path to be configured properly   
      $mail_sent = mail($to, $subject, $content, $headers, $returnpath);
        //Note I don't do any error checking on $mail_sent because mail() often produces strange return codes yet works
 
        //Tell them they are blocked (even though you allowed
        //the message through) to discourage future attempts
          if ($block==0) header('Location: http://www.example.com/_thankyou.htm');
            else header('Location: http://www.example.com/_block.htm');                 
}   
?>
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: This should be easy???

Post by Eric! »

Do you know if filter_var is comprehensive? I haven't been able to find what it is doing other than just vague statements. When I started looking into email validaton I was surprised how complex it can be. It would be nice if it works right, but it won't help with dns checking.
Post Reply