OSdata.com: holistic issues 


how to create a contact form in PHP

    A real world example of how to create a simple contact form using PHP. You can expand this in many different ways.

example source code

    Building a game — open source code This is the actual source code from a new web game. See the game at thissideofsanity.com and read how this was built starting at example code.

    This is example code from the SlamZee project and This Side of Sanity, released under Apache License 2.0.

    Copyright 2013 Milo (for software), Distribution and website handled by Strazbick.com

    Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at


    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

    This narrative uses anchor links so that you can follow the building of this software in chronological order. Go to software explanation to start reading. Go to thissideofsanity.com to see the working software.


example source code

first pass example
display and process contact form

    Show the contact form and process it when sent.

    Note that the form is displayed in a function, so you can insert the form on any web page on you website by just calling the function. Also notice the hidden field for identifying which page the form was sent from. This ID can be used on generated pages to distinguish where someone is in your system.

    Please realize that the DisplayContactForm function will need to be moved to your utilities file and you need to use the appropriate include or require_once to insert it into a live web page.

    I copied the code from another web site, which have done repeatedly before. While preparing this for the website, I noticed that a bunch of the comments described special cases or obsolete cases. This highlights one of the dangers of comments: because comments are not active code, there is no compiler failure when they become outdated or misleading. The only reason they got cleaned up this time is because I am publishing the source code on the internet.


/* CONFIGURATION              */
/* Set the domain name and outgoing email addresses to match your needs */
    $outgoingemailaddress = 'example@gmail.com,example@yahoo.com,example@hotmail.com';
    $domainname = 'slamzee.com';

/* GLOBALS                    */

/* FUNCTIONS                  */

/* DisplayContactForm                        */
/* display the contact form                  */
/* is a function so can be used on any page  */
function DisplayContactForm()

/* Change the website where the form is submitted. And feel free to change the design and the items submitted to match your needs. */


<h1 align="center">Contact</h1>

<form action="http://www.slamzee.com/contact.php" method="post">
<table align="center" border="0"><tr><td colspan="2">
<h3 align="center">please contact us</h3></td></tr>
<tr><td align="left">your name:</td><td align="left"><input type="text" name="visitorname" size="35"></td></tr>
<tr><td align="left">email address:</td><td align="left"><input type="text" name="emailaddress" size="35"></td></tr>
<tr><td align="left">phone number:</td><td align="left"><input type="text" name="phonenumber" size="35"><input type="hidden" name="pageIDcode" value="<?php echo $pageIDcode; ?>""></td></tr>
<tr><td colspan="2" align="center">message:<br><textarea name="comments" cols="40" rows="6"></textarea></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="contact us"></td></tr></table>


} /* END DisplayContactForm */

/* MAIN PROCESING             */

  { /* display the contact form */

    $inputflag = false;

  { /* collect input */

    $inputflag = true;

/* If you add or delete items on your form, make this match. */

    $visitorname = $_POST["visitorname"];
    $emailaddress = $_POST["emailaddress"];
    $phonenumber = $_POST["phonenumber"];
    $comments = $_POST["comments"];
    $article = $_POST["article"];
    $pageIDcode = $_POST["pageIDcode"];


/* Modify this header and metatag information to match your website needs. */

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en" dir="ltr">

<!--FILE NAME /contact/contact.php-->

<head><title>SlamZee: Contact</title>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"></meta>
<meta name="revisit-after" content="90 days"></meta>
<meta name="robots" content="all"></meta>
<meta name="description" content="SlamZee: Contact"></meta>
<meta name="keywords" content="SlamZee contact"></meta>
<meta name="creation" content="2013-07-01"></meta>
<meta name="last-modified" content="2013-10-10"></meta>
<meta name="MSSmartTagsPreventParsing" content="TRUE"></meta>
<link rel="stylesheet" type="text/css" href="./style.css">

<body text="#000000" class="main">

<h1 align="center" style="width:320px;background-color:black;margin-left:auto; margin-right:auto;text-align:center;font-family:Geneva,sanserif;font-size:48px"><span style="color:red">Slam</span><span style="color:yellow">Z</span><span style="color:green">ee</span></h1>


<table align="center" border="2"><tr align="center">
<td><a href="./index.php">play game</a></td>


/* if ($inputflag) I now use the comments test to delete empty form submissions */
if (trim($comments) != '')
  { /*comment received, process form*/

    if (trim($visitorname) == '')
        $visitorname = 'NONE GIVEN';
        $visitorname = htmlentities($visitorname);

    if (trim($emailaddress) == '')
        $emailaddress = 'NONE GIVEN';
        $emailaddress = htmlentities($emailaddress);

    if (trim($phonenumber) == '')
        $phonenumber = 'NONE GIVEN';
        $phonenumber = htmlentities($phonenumber);

    if ($comments == '')
        $comments = 'NONE GIVEN';
        $comments = htmlentities($comments);

/* be careful about allowing MIME attacks */
/* the outgoing email addresses and the domain name are now set at the top of the script */

    $subjectline = 'Contact from '.$domainname;
    $messagecontent = "Message from ".$domainname."\nDO NOT REPLY TO YOUR SERVER!\nNAME: ".$visitorname."\nEMAIL: ".$emailaddress."\nPHONE NUMBER: ".$phonenumber."\nMESSAGE:\n".$comments."\nPAGE: ".$pageIDcode;

    if ($article != "")
      $messagecontent = $messagecontent."\nFROM WEB PAGE: ".$article;

    $fromaddress = 'From: postmaster@'.$domainname;

    mail($outgoingemailaddress, $subjectline, $messagecontent, $fromaddress);

    echo '<p align="center'>Thank you for your message, '.$visitorname.'</p>';

    echo '<p align='center'>You told us: '.$comments.'</p>';

else /* no comment received, so display a form */


  } /* END ELSE */


<h3 align="center"><a href="./index.php">play another game</a></h3>



    A discussion at Google+ brought up the issue of mime injections. As pointed out by Andrew Riley, it is possible for a malicious person to use curl (or other similar tool) to insert extra mail headers into a form submission and hijack your server to send out email spam.

    That security hole does not apply to this script as written because all user input is in the message field and the mail() function will filter any content in that field to prevent it from being abused. Nonetheless, it is important to keep mime injections in mind as you modify this script for your own purposes.

    For more information on mime injections into emails, see Email Injection and Wikipedia.

    Stewart Souter recommended “adding the sender’s IP address just so it can be traced”. The information that can be gathered in PHP varies greatly by server. The following code might collect the IP address (which can then be appended to the message):

if ( isset($_SERVER["REMOTE_ADDR"]) )
  $ip = $_SERVER["REMOTE_ADDR"];
elseif  ( isset($_SERVER["HTTP_X_FORWARDED_FOR"]) )
elseif  ( isset($_SERVER["HTTP_CLIENT_IP"]) )


    Stewart Souter recommended an improvement. The script now uses trim to eliminate leading and trailing spaces (actually all whitespace, including ordinary space, tab, new line, line feed, carriage return, vertical tab, and the NUL-byte). The trimmed inputs are then checked to see if they are empty to avoid additional kinds of empty messages.

    Tim Garrison recommended moving the outgoing email addresses to “a configuration directive towards the top of the script, just to make setup easier”. I moved that item to the top of the file and also changed all of the domain name entries from hard-coded to a variable. Set or change both of these from a convenient location.

    You can play the game and then use the form to send feedback suggestions and comments. Just go to SlamZee.com. Work on the game just recently started and the entire game source code (minus security information) is being published as open source under the Apache 2.0 license, so you can freely take ideas for your own work (subject to the license restrictions). And please use the form to submit ideas for improvements. Even better if you share your improved source code.

return to explanation of source code

OSdata.com is used in more than 300 colleges and universities around the world

Find out how to get similar high web traffic and search engine placement.

OSdata.com is used in more than 300 colleges and universities around the world

Read details here.

    A web site on dozens of operating systems simply can’t be maintained by one person. This is a cooperative effort. If you spot an error in fact, grammar, syntax, or spelling, or a broken link, or have additional information, commentary, or constructive criticism, please e-mail Milo. If you have any extra copies of docs, manuals, or other materials that can assist in accuracy and completeness, please send them to Milo, PO Box 1361, Tustin, CA, USA, 92781.

    Click here for our privacy policy.

previous page next page
previous page next page

home page

Made with Macintosh

    This web site handcrafted on Macintosh computers using Tom Bender’s Tex-Edit Plus and served using FreeBSD .

Viewable With Any Browser

    Names and logos of various OSs are trademarks of their respective owners.

    Copyright © 2013 Milo

    Last Updated: October 13, 2013

    Created: October 10, 2013

previous page next page
previous page next page