This is a simple php contact form / feedback form script I through together as an introduction to php for a friend.
Rather than write a tutorial I’ve heavily commented the code. Hope its useful to somebody.
WARNING – This was written a long time ago, and does not reflect current PHP best practice!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 |
<?php /* Turn on php's error / warning reporting system to show EVERY error message, notice and warning. This is helpful for debugging scripts. see www.php.net/error_reporting On an active website you might turn this down or off so that if an error occurs you don't give the visitor any information about how your site works that might be of use to an attacker. */ error_reporting( E_ALL); /* A simple php contact form This script displays an html page containing a form and when that form is submitted the script processes the submitted values and sends them as an email. It's a pretty simple script, but introduces a lot of the commonly used topics in php. I'd recommend skimming over the w3schools tutorials on php before trying to understand this, or flipping between this and them. http://w3schools.com/php/default.asp ps, this stuff in between the slash-asterisk....asterisk-slash is a comment You can also have single line comments that begin with // So its basically the same as java for comments Also it makes it easier to edit / view php code if the text editor you use has syntax highlighting (using different colours for variable names, comments, etc.) I use htmlkit (the free version 292) http://www.chami.com/html-kit/download/ but have heard good things about notepad++ http://notepad-plus.sourceforge.net/uk/site.htm If you want an easy to setup php / apache / mysql package try http://www.en.wampserver.com/ */ // first initialize some variables that will be used to hold the values in // the contact form. Doing this enables us to redisplay the values the user // enters in case they leave some fields blank and we ask them to complete // everything... // Note that all variable names in php begin with the dollar sign $ // see http://uk2.php.net/language.variables for more info about variables in php // the email address the submission will be sent to // put your own address here // the example.com domain name is reserved specifically for use in tutorials and examples // like this one. $my_email = 'youremailhere@example.com'; $name = ''; // will just hold the person's name $subject = 'Hello'; // will hold the subject of their email. We give a default value of "Hello" $email = ""; // the email address $message = ""; // their message // note above that php can either use two double quotes or two single quotes to enclose a string // the difference is that strings using double quotes can contain other variables // eg. if we had $somestring = "$subject World"; (using the $subject variable above, then // $somestring would contain 'Hello World'. $submitted = false; // we will set this to "true" if the user successfully submits the form $errors = array(); // create an empty array to hold any error messages we may want /* Here we check if the user has submitted the form. http://www.w3schools.com/php/php_post.asp and http://www.w3schools.com/php/php_get.asp provide a bit of info on what the GET and POST methods are used for. These are a simple but *extremely* important concept for php programming as they are how scripts get input / data from the user. */ // if the user has submitted the form (by pressing the "Send" submit button, then the value // of this button will be in the $_POST array with the key / name 'send' // // php arrays are similar to java hashmaps, but with a much simpler syntax to use them. // see the php manual http://uk3.php.net/manual/en/language.types.array.php or // w3schools http://www.w3schools.com/php/php_arrays.asp // php array article for why it is written $arrayname['keyname'] if( isset( $_POST['send'] ) ){ // isset is a function that tests if a variable is "set", that is "defined" // get the form values for each variable we want // the trim() function just removes any extra white space (spaces, tabs, etc) from the variable $name = trim( $_POST['name'] ); $subject = trim( $_POST['subject'] ); $email = trim( $_POST['email'] ); $message = trim( $_POST['message'] ); // check that the user has filled in everything by ensuring they have at least typed *something* in // each field. The minimum required length is hard-coded below. // check the name is at least 2 characters long. // strlen() is a function that checks the length of a string, if( strlen($name) < 2 ){ // name too short, lets inform the user. // in php you assign something to the end of an array // by using the [] empty square brackets $errors[] = 'You must enter your name'; } // check the length of the subject and message if( strlen($subject) < 2 ){ $errors[] = 'Please enter a subject for your message'; } if( strlen($message) < 5 ){ $errors[] = "You haven't written a message :("; } // we should do some better validation of the email address to make sure it is a real // one but here i'm just using a simple regular expression to check it looks sorta ok // regular expressions are very useful and powerful but take a while to get your head around // the pattern below basically matches any string that: see http://uk3.php.net/manual/en/book.pcre.php for info on regular expressions // i) begins with one or more of the letters a-z, the numbers 0-9, _ . or - // ii) followed by the @ sign // iii) followed by one or more letters, numbers _ . or - // iv) followed by another ., followed by one or more letters // eg. someone @ example .com // (i) (ii) (iii) (iv) if( !preg_match('/^[a-z0-9_.-]+@[a-z0-9_.-]+.[a-z]+/i', $email) ){ $errors[] = "How can I reply to you if you don't give me a valid email address?????"; } /* one last but important step is to check the user submitted values aren't a spammer trying to hijack our form to send spam emails on their behalf. This isn't something I'm going to go into in any detail here, but is important to know about: for more information see: http://www.thesitewizard.com/php/protect-script-from-email-injection.shtml http://www.phpit.net/article/php-security-3-example-exploits/ We use a simple regular expression to only allow the letters a-z, numbers 0-9 and a few bits of punctuation in our email address, name and subject fields. Basically we don't let the user submit anything that might be dodgy, although this does mean we can't have submissions using characters that aren't in the english language. Which might suck a bit. */ $testRegEx = '/^[a-z0-9!"():;@#/\.,<>_ -]*$/i'; if( !preg_match($testRegEx, $name) || !preg_match($testRegEx, $email) || !preg_match($testRegEx,$subject) ){ $errors[] = 'Your name, email address or subject contained invalid characters. Please re-enter.'; } // if we have found any errors then we don't want to send the email // we can tell if there are any errors by checking the number of entries in // our $errors array. // In php you check the size / number of items in an array using the count() function if( count( $errors ) == 0){ // no errors, send the email using php's mail($to, $subject, $message, $headers) function // first we create two more strings $full_subject and $full_message which // will contain slightly modified versions of the original // we prepend 'Contact form submission' to the user's subject, so when it shows up in our // email client we know it came from our form // Notice that php concatenates strings using the period . not a + like in java. $full_subject = 'Contact form submission: ' . $subject; $full_message = "$name sent the following message at " . date('H:i:s') . ' on ' . date('l jS F Y'). " from ip address {$_SERVER['REMOTE_ADDR']}nn"; $full_message .=$message; // ok should probably explain what the two lines above do :0) // "$name sent..." places the contents of the $name variable into the string // date('H:i:s') gets the current time in the format 12:01:54 (hours:minutes:seconds) // date('l jS F Y') gets the current date in the format "wednesday 16th July 2008" // see www.php.net/date for more info (and note that you can access php info quickly at // php.net by placing what you are looking for after the domain name, eg. php.net/arrays php.net/strings // the {$_SERVER['REMOTE_ADDR']} imbeds the ip address of the current user into the string as well. // $_SERVER is an array containing info from the server. array entries can be embedded in strings by // surrounding them with curly brackets {...} $full_email = "$name <$email>"; // the $headers parameter to the mail() command adds some important headers to the email, such as from and reply-to addresses. $headers = "From: $full_emailrnReply-To: $full_emailrnErrors-To: $my_email"; // on your home pc, the mail function may not be able to work ok and will output an error. if( mail($my_email, $full_subject, $full_message, $headers) ){ $submitted = true; // we use this variable later to decide whether to show the form or a thank-you message } else{ // if mail() failed then we have a server configuration error... $errors[] = 'Sorry, due to server issues your message could not be sent. Please try talking to me instead :p'; } } } /* thats's most of the code, now we come out of php mode and add an html page containing a simple form. we mix a bit of php with it to check: 1) has the form been submitted? if so then just display a message, no form 2) if displaying the form, are there any errors? if so, display them 3) we output / echo / print any values the user has already submitted for the form 4) we echo the uri of this script into the form's action="" parameter so that the form submits back to this page A couple of notes about a couple of functions used below: htmlspecialchars() takes a string and returns the same string with any characters that have special meaning in html converted to display properly. nl2br() Converts any newline characters in the string to html <br /> line break tags (because html just treats newlines as spaces. echo is a php function that prints the values of its parameters to the screen. You could also use print() */ ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Contact Us</title> </head> <body> <?php // if the form has been successfully submitted, just display a message showing what was sent: if( $submitted ){ ?> <h1>Thank You!</h1> <p>Thank you for contacting us. The following message was sent from <?php echo htmlspecialchars($name)?>, <?php echo htmlspecialchars($email)?>:</p> <p>Subject: <?php echo htmlspecialchars($subject)?></p> <p>Message: <?php echo nl2br(htmlspecialchars($message))?></p> <?php } else{ // otherwise display the form ?> <h1>Contact Us :)</h1> <?php if( count( $errors ) ){ ?> <div style="font-weight: bold; color: red;"> <h2>Please correct the following errors and resubmit the form:</h2> <?php foreach( $errors as $error ){ echo '<p>' . htmlspecialchars($error) . '</p>'; } ?> </div> <?php } // end of test for error messages ?> <form action="<?php echo $_SERVER['SCRIPT_NAME']?>" method="post"> <br /> Your Name: <input type="text" name="name" value="<?php echo htmlspecialchars($name)?>" /> <br /> Your Email: <input type="text" name="email" value="<?php echo htmlspecialchars($email)?>" /> <br /> Subject: <input type="text" name="subject" value="<?php echo htmlspecialchars($subject)?>" /> <br /> Message: <textarea name="message" cols="60" rows="20"><?php echo htmlspecialchars($message)?></textarea> <br /> <input type="submit" name="send" value="Send Message" /> </form> <?php } // end of the if statement that checks if the form has been successfully submitted ?> </body> </html> |
Feel free to send me some feedback on this if you found it useful :0)
This is exactly what I needed, and super-easy to understand. Thanks!