1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Development Contact form in PHP

Discussion in 'Software' started by voodoo2k4, 10 Oct 2008.

  1. voodoo2k4

    voodoo2k4 Ghetto Modder

    Joined:
    21 Apr 2004
    Posts:
    316
    Likes Received:
    2
    A simple ne for you gurus....

    So yer I know I should know how to do this but although Im happy as with HTML and CSS, Im not PHP or any other language. Now a clients making me add a few PHP bits to a site, Im a bit lost.

    Soooo... I need two very simple forms on this site, basically just contact us type forms. The forms are all done and look nice in the pages:


    Code:
    <p>Using this enquiry form:</p>
                    
            <table width="550" border="0" align="center" cellpadding="0" cellspacing="0" id="applicationform">
            <tr>
              <td width="300"><label for="firstname">First name:</label></td>
              <td><input name="firstname" type="text" id="firstname" maxlength="30"></td>
            </tr>
            <tr>
              <td><label for="surname">Surname:</label></td>
              <td><input name="surname" type="text" id="surname" maxlength="30"></td>
            </tr>
            <tr>
              <td><label for="email">Email address:</label></td>
              <td><input name="email" type="text" id="email" maxlength="30"></td>
            </tr>
            <tr>
              <td height="243"><label for="artdetails">Please enter your question or request here:</label></td>
              <td><textarea name="artdetails" id="artdetails" cols="45" rows="15"></textarea></td>
            </tr>
              <tr>
             	<td>&nbsp;</td>
             	<td><br><input name="submit" type="submit" class="submit" id="submit" onClick="MM_validateForm('firstname','','R','surname','','R','email','','RisEmail','telephoneno','','NisNum','mobileno','','NisNum','date','','R');return document.MM_returnValue" value="Submit"><br>&nbsp;</td>
             </tr>
          </table>

    But I have no idea how to process this form server side and get it sent in a very basic email to a specified address. I gather I need some kind of simple PHP file to process the data and spit it out as an email.

    Help! Usual leaving it too late to tie up loose ends and the site would look much smarter with these forms on there, and working!

    Im on the developer package at Fasthosts too which I presume has all I need to run this?!¬!

    Thanks for any help/pointers, :) Yu have also reminded me to use the CODE function when pasting code!

    Dean.
     
    Last edited: 13 Oct 2008
  2. NiHiLiST

    NiHiLiST New-born car whore

    Joined:
    18 Aug 2001
    Posts:
    3,987
    Likes Received:
    6
    There's a beginner tutorial here. Should be fairly easy to follow and you should start to pick up a few bits and pieces.
     
  3. AlexB

    AlexB Web Nerd

    Joined:
    22 Dec 2005
    Posts:
    2,446
    Likes Received:
    74
    Also, dont use tables for forms. *slaps wrists*
     
  4. Cinnander

    Cinnander What's a Dremel?

    Joined:
    19 Apr 2007
    Posts:
    393
    Likes Received:
    2
    Tables are fine for forms, even in HTML 4 strict. Less so in XHTML, admittedly.
    The linked tutorial covers it pretty well - I'd subject everything to a bit more scrutiny before sending email (check the contents of post a bit more thoroughly and strip \0 out of the message for example - though it doesn't need much).

    If you're new to PHP some things - especially when dealing with forms - to be aware of
    a) magic_quotes_gpc and magic_quotes are often enabled in new PHP installations. They are annoying, though they add a layer of 'safety'. I'd recommend you turn them off, otherwise everything you post will have spurious escaping (\) appearing which can be tricky to get rid of - especially if your messages require people to actually send things like code samples. It's a good idea to get into the habit of securing your input yourself anyway. GPC stands for Get/Post/Cookie, i.e. the magic_quotes as applied to $_POST, $_GET, $_COOKIE. I think you have to turn it of in php.ini though, which requires a webserver restart/reload - hopefully your host already has it turned off.
    b) Make sure register globals is off. It's been disabled by default for years now. If it's on, you basically end up with a variable for every <input> on your form. So <input name="foo"> becomes $foo. Anyone posting to this script can essentially overwrite any variable they want.
    c) Make a file with the following in it:
    <?php phpinfo(); ?>
    It will be very useful, and initially somewhat educational. Do not call it phpinfo.php (see results 6-9, 13, 16). If you're not sure what 'state' php is in after you post or do something, just set the form target to the phpinfo() containing file and you can see the entire state, of the environment. Don't put anything else in that file - the phpinfo() command is essentially a page-in-a-function. A hackish alternative with just the important bits is:
    PHP:
    $information = array('Get'=>$_GET'Post'=>$_POST'Server'=>$_SERVER'Cookie'=>$_COOKIE);
    foreach(
    $information as $global => $content) {
      echo 
    "<h1>$global</h1>";
      echo 
    "<pre>" print_r($contenttrue) . "</pre><hr />";
    }
    This just creates an array containing each of the superglobal arrays, then loops over them printing their content. Again, you can post/link to this to see what's up. $_SESSION is another useful one if you're doing anything that requires login.

    Relevant docs: superglobals, print_r(), foreach(loop), array() (Arrays)
    And for your mailing form: mail()
     
    Last edited: 11 Oct 2008
  5. Firehed

    Firehed Why not? I own a domain to match.

    Joined:
    15 Feb 2004
    Posts:
    12,574
    Likes Received:
    16
    Tables are WRONG for everything except tabular data. Forms are not tabular data. They can create the desired effect, sure, but that doesn't stop them from being a semantically retarded unmaintainable nightmare. Your DTD has nothing whatsoever to do with creating maintainable code - most of the crap that comes from Dreamweaver validates, but that doesn't stop it from being an utter mess.

    Anyways, a contact form is fairly simple - depends whether you want to email or send the results to a DB, or both. Sounds like you want to email stuff. Here's a simplified version of what I have on my portfolio contact form:
    PHP:
    <?php
    if (isset($_POST['submit'])) {

        if (
    get_magic_quotes_gpc() && !empty($_POST)) {
            foreach (
    $_POST as $key => $value) {
                
    $_POST[$key] = stripslashes($value);
            }
        } 
    // strip out any slashes from magic_quotes, sanitize later if adding to DB


        
    $email = array();

        
    $email['subject'] = $_POST['subject'];
        
    //do for each field in the form

        
    $to 'YOUREMAIL@example.com';
        
    $subject 'Portfolio contact form: ' $email['subject'];
        
    $body = <<<BODY
    {
    $email['name']} has just filled out the contact form on your portfolio with the following information.  Please contact him/her as soon as possible.

    Name: 
    {$email['name']}
    E-mail Address: 
    {$email['email']}
    Subject: 
    {$email['subject']}
    Phone: 
    {$email['phone']}
    Website: 
    {$email['website']}
    Message:

    {$email['message']}
    BODY;

        
    $headers = <<<HEAD
    From: {$email['name']} <{$email['email']}>
    Reply-To: 
    {$email['name']} <{$email['email']}>
    X-Mailer: PHP/contactform
    HEAD;

        
    $body wordWrap($body70);
        
        
    //Send the message        
        
    $mailSent mb_send_mail($to$subject$body$headers);
            
    }

    if (isset(
    $mailSent) && $mailSent == true) {
        echo 
    'Thanks for contacting me.';
    }
    else {
        
    //HTML for your form goes here, action = this page
    }
    ?>
    Don't just copy and paste the code though, if you intend to use it- actually understand what's going on. Since my servers running magic_quotes_gpc is a crapshoot I just have an if-check, and strip out the slashes added by them if it's turned on. If I were to add this information into the database, I'd sanitize it for SQL injection and whatnot later. No need to worry about that right now, really. I then make an array called $email with each of the fields from the form as a key. In the live version I have it done a bit differently (most of it happens automatically since I have form names like email[name], email[phone] etc and that throws them into the array for me). Anyways from there I just format the body of the email, using the heredoc syntax (the <<<BODY thing), same for the mail headers, and then send it using the mb_send_mail command. It's only different from the normal mail() command in that it handles multi-byte character encodings like UTF-8 much more nicely than the standard version. If it worked, I throw up a nice little thank you message, otherwise I re-display the form. I also have various bits of validation in place to make sure required fields are filled out and to display an error message if that's not the case.
     
  6. voodoo2k4

    voodoo2k4 Ghetto Modder

    Joined:
    21 Apr 2004
    Posts:
    316
    Likes Received:
    2
    Wow! You guys are legends. Ive always used bit-tech for hardware/modding rambling, I never realised there was such a wealth of developers/coders on here. Awesome! (-guitar-)

    NiHiLiST - Thanks for the tutorial link, I am definately going to need some of that and it seems to be quite clear. :lol:

    Firehed and Cinnander, I cant belive you guys even stuck up your code for me to use. Im going to give your replies the time they deserve tommorow or wednesday as Im tied up today . Im not going to copy n paste as I really need to 'get it' so that I can use it other sites in the future and hopefully be bale to build on it as I also have an online application form Ive just laid out that will work in a similar way but has a few more and varied input fields etc

    I will report back with my pathetic failures soon. And I might even ask a question about thumbnail image click pop up type things too when this is done now that I know the expertise thats out there :idea:!

    Dean.
     
  7. tominated

    tominated What's a Dremel?

    Joined:
    28 May 2008
    Posts:
    504
    Likes Received:
    6
  8. NiHiLiST

    NiHiLiST New-born car whore

    Joined:
    18 Aug 2001
    Posts:
    3,987
    Likes Received:
    6
    One of my favourite photo-popper-uppers is Remooz.
     
  9. voodoo2k4

    voodoo2k4 Ghetto Modder

    Joined:
    21 Apr 2004
    Posts:
    316
    Likes Received:
    2
  10. koola

    koola Minimodder

    Joined:
    11 Jul 2004
    Posts:
    2,462
    Likes Received:
    10
    One of mine too :thumb:

    @Voodoo

    Don't forget to run the fields submitted through some validation. I like regex for this task, here's a regex for the email:

    Code:
    "^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$"
     
  11. Firehed

    Firehed Why not? I own a domain to match.

    Joined:
    15 Feb 2004
    Posts:
    12,574
    Likes Received:
    16
    FancyZoom does the same thing w/out the MooTools requirement, FYI. Not that I have any issue with MooTools, but it never plays nice with jQuery which is always a problem for me :/ http://www.cabel.name/2008/02/fancyzoom-10.html

    And yes, definitely validate the fields. As I mentioned, I've got some other validation code in place on my full implementation, basically a bunch of isset() calls. I don't bother validating whether email addresses are well formed because a) regex gives me headaches and b) I don't want to deal with people that can't type their email address correctly.
     

Share This Page