WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search


Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder



Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : The Nearly Perfect Contact Us Form
Categories : PHP, Form Processing, HTML and PHP Update Picture
Joshua Walcher
Date : Apr 02nd 2009
Grade : 2 of 5 (graded 6 times)
Viewed : 10597
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Joshua Walcher
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

This is my contribution to the PHP world for contact us message processing that blocks spammers and hackers, validates forms, emails valid results only. In other words, what it's supposed to do.

I'm on a one-page PHP kick right now, so I'm going to do both the HTML form and the PHP code to process it on the same page. Just save this file as example.php somewhere. My comments are throughout.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Josh's Nearly Perfect Form Example</title>
<style>
body{
    background: #fff;
    font-size:16px;
}
a{
  text-decoration:none;
}

.container{
    width:950px;
    margin-left:auto;
    margin-right:auto;
}
.enter{
    position:relative;
    top:120px;
    height:250px;
    width:400px;
    margin-left:auto;
    margin-right:auto;
    padding:24px;
}

.footer{
    border-top:1px #ccc;
    width: 960px;
    position:absolute;
    bottom:0;
}
.head{
    font-size:22px;
    font-family:Verdana, Rockwell, Arial, Helvetica, sans-serif;
    font-weight:bold;
    padding-top:8px;
}
</style>

<body onload="document.form.name.focus()">

<div class="container">
<div>

<?php
// This will only process the form if the form has been posted to it.
if($_SERVER['REQUEST_METHOD']=='POST') {
   
        if(
$_POST['name']){
       
/* they posted the name, but we still need to validate it to see if they're dirty rotten spammers */
               
if(substr_count($_POST['name'],'<') > 1 || substr_count($_POST['name'],'>') > 1){
           
$error[] = "You dirty rotten spammer, you. Stop submitting links or I'll hunt you down.";
        }else{
                 
$name = $_POST['name'];
         
/* create a session for the variable in case there are errors, we don't want them to have to enter the whole form again! */
                 
$_SESSION['name'] = $name;
                }
    }else{
               
/* create an array of error messages */
       
$error[] = "You need to enter your name.";
    }
    if(
$_POST['email']){
               
/* there was something entered, but was it an email? */
       
$email = $_POST['email'];
       
/* $e = email pattern */
               
$e = "/^[-+\\.0-9=a-z_]+@([-0-9a-z]+\\.)+([0-9a-z]){2,4}$/i";
       
//
       
if(!preg_match($e, $email)){
       
/* then the email doesn't match the pattern */
               
$error[] = "Your email address isn't valid";
        }else{
               
$_SESSION['email'] = $email;       
            }
    }else{
       
$error[] = "You need to enter your email address.";
    }
    if(
$_POST['message']){
       
/* We've got something, so let's check for spammers */
               
if(substr_count($_POST['message'],'<') > 1 || substr_count($_POST['message'],'>') > 1){
           
$error[] = "You bad, bad spammer, you. Stop submitting links or I'll hunt you down.";
        }else{
           
$message = $_POST['message'];
           
$_SESSION['message'] = $message;       
        }
    }else{
       
$error[] = "You need to enter a message.";
    }
   
/* ok, if we have an error, then we need to show them to the user, but also keep the valid data in the form and just delete the data that didn't pass validation */
       
if($error){
        foreach(
$error as $e){
            echo
"<b>" . $e . "</b><br>";
        }
    }else{
       
/* We passed validation so kill the session (you may not want to do this if you're using sessions on your site. You can just unset the session variables we set above. */
               
$_SESSION = array();
               
/* wrap the message every 70 characters for readability */
       
$message = wordwrap($message, 70);
       
/* This is a little silly, but you never know about spammers, so let's remove the gt & lt signs from the message just in case */
               
$message = str_replace("<","",$message);
       
$message = str_replace(">","",$message);
       
/* and while we're at it, let's remove their URL openings too */
               
$message = str_replace("http://","",$message);
       
$message = str_replace("www.","",$message);
       
/* Now that the message is scrubbed, add the IP address to the end of it so that we can block anyone that overmails us */
               
$message = $message . "\n" . $_SERVER['REMOTE_ADDR'];
               
/* Pretty standard stuff from here on out */
       
$headers  = 'MIME-Version: 1.0' . "\r\n";
       
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

       
/* Additional headers */
       
$headers .= "To: Your Name <[email protected]>" . "\r\n"; //CHANGE THIS TO BE YOUR OWN EMAIL ADDRESS!!!
       
$headers .= "From: $email" . "\r\n" . "Reply-To: $email" . "\r\n";
       
       
mail("[email protected]","Message from the Nearly Perfect Form User $name",$message,$headers);
        echo
"Thanks for the message!";
    }
}
?></div>
<div class="enter" align="center">
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div align="center" class="head">Contact Us</div>
<br />
<table><tr><td><div align="right">Your Name</div></td><td><div align="left">
  <input name="name" size="30" maxlength="50" value="<?=$_SESSION['name'];?>" />
  *</div></td></tr>
<tr><td><div align="right">Your Email</div></td><td><div align="left">
  <input name="email" size="30" maxlength="70" value="<?=$_SESSION['email'];?>" />
  *</div></td></tr>
<tr><td valign="top"><div align="right">Message</div></td><td><div align="left">
  <text area name="message" cols="26" rows="4"><?=$_SESSION['message'];?></text area>
  *</div></td></tr>
<tr><td> </td><td><div align="left">
  <input type="submit" value="Send Message" />
</div></td></tr></table>
</form>
</div>
<div class="footer" align="center">
        <div class="clear"> </div>
</div>
</div>
</body>
</html>



Dynamic form field
Categories : PHP, HTML and PHP, Form Processing
PHP3: Formmail. Just a cgi formmail, but than in PHP. It is easy to use!
Categories : HTML and PHP, Email, PHP, Perl, HTML and PHP
Sql Builder
Categories : PHP, HTML and PHP, Databases, General SQL, Form Processing
Simple PHP Form Field Generator
Categories : PHP, Beginner Guides, Form Processing, HTML and PHP
PHP based HTML rabbing Tools
Categories : PHP, HTML and PHP, Tag Extractors, Regexps, Beginner Guides
A simple php file uploader
Categories : PHP, Filesystem, HTML and PHP
addslashes automatically to $_POST variables
Categories : PHP, Form Processing, Security
Using select multiple with php3
Categories : HTML and PHP, PHP
background music script for random notes in a frame
Categories : PHP, Content Management, HTML and PHP
Simple class to build tables with style sheets
Categories : HTML and PHP, PHP Classes, PHP
function textwrap will wrap text to any desired width using <BR>\n as the default line break. Default wrap width is 80 columns.
Categories : Strings, HTML and PHP, PHP
PHP MultiList Mailing List Manager
Categories : Email, HTML and PHP, PHP
How to use regular expressions to get the list of links from an HTML page
Categories : PHP, Regexps, HTML, HTML and PHP
Dynamic CSS generation for multiple website colouring schemes.
Categories : PHP, CSS, HTML and PHP
Dynamic Page
Categories : Frameworks, PHP, HTML and PHP
 Luiz Araujo wrote : 1831
Thanks for this nice script.
It works fine if I use <textarea> instead of <text area>.
 
 Donald Grouns wrote : 1832
Just a short note to say that when I first tried the 
script both in my Kompozer WYSIWYG and EditPlus3 and then 
also on my server the message box in the form did not 
show. I looked again at the code and see that there is an 
error in Line 133 (at least on my code page) instead of

<textarea name="message" cols="26" rows="4">
<?=$_SESSION['message'];?>
</textarea> 

it should be:

<textarea name="message" cols="26" rows="4">
<?=$_SESSION['message'];
?>
 
 Terry Wysocki wrote : 1833
Also, you have to name the file "contact.php" on your 
server. Otherwise adjust the line that says 
action="contact.php" to whatever you name the file.
 
 Donald Grouns wrote : 1834
One additional note...  for dummies like me, for this 
script to work it needs to be named contact.php or the 
line in the code showing the "form action" needs to be 
changed to whatever the page name you choose, of course 
with a .php extension.
 
 Nathan Sepulveda wrote : 1835
When offering code to the public that posts back to itself, I would recommend using $_SERVER['PHP_SELF'] instead of a page name that. that way there are no naming issues involved.

ex:

[CODE]
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
[/CODE]
 
 Greg Schiedler wrote : 1836
Code needs some work or possibly a line to download the 
code.  I have tried it on several machines and two 
different connections.  All fail to show a message box 
that you can type anything into.
 
 Joshua Walcher wrote : 1837
I know that nobody is reading these comments, but yes, it should be:
input type="textarea"
instead of:
input type="text area".

WeberDev doesn't offer any method of editing after submission.

Additionally, the opening form tag should say either the name of the file you are on or:
<?php echo $_SERVER['PHP_SELF']; ?>
as the action.
 
 Boaz Yahav wrote : 1838
Actually someone from weberdev makes an effort to read all 
comments and make needed changes. You can always contact 
us to pdate code.
 
 Joshua Walcher wrote : 1839
Sorry, wasn't meaning to insult WeberDev. Thanks for the 
updates to the script and I'll make sure my shiznit is in 
order next time I submit.
 
 Boaz Yahav wrote :1840
The most important thing is to keep submitting code examples :)