PHP email script

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
Andorphin
Forum Newbie
Posts: 7
Joined: Fri Oct 31, 2008 3:44 am

PHP email script

Post by Andorphin »

Hi everyone

New to the site, but looking for a huge help. I have a php script that was givnen to me, What I want it to do is validate a contact form and highlight any validation errors beside the relevant field.

I want the customer to be only able to uplad .jpg images, with a max image size of 250x160.

I then want it to send all the information gathered to me in a formatted email - this I just need a quick starter on, as i feel this part I could do myself. But the others are jus beyond me as I am not good at php and trying to learn.

I do know that I am asking for a lot of help, but I do appreciate the time taken to read this and thank anyone who can help in advance.

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
 
<head>
 
<title>Rent in Fife</title>
        <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
        <meta http-equiv="Content-Language" content="en-us" />
        <meta http-equiv="imagetoolbar" content="no" />
        <meta name="MSSmartTagsPreventParsing" content="true" />
        <meta name="description" content="Description" />
        <meta name="keywords" content="Keywords" />
        <meta name="author" content="Colin Burt" />
 
        <style type="text/css" media="all">@import "includes/stylesheets/default.css";</style>
 
        <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA55lo0C46TQhEnHj8DQBTtxTaQ5dQGm2LYPeImFe76gdZiHRAAxSDRuKZPK91669NrlMj5ollP4Hp3Q" type="text/javascript"></script>
        <script src="includes/javascript/map_search.js" type="text/javascript"></script>
 
</head>
 
<body onload="Load()" onunload="GUnload()">
 
<!-- Page body container starts here -->
    <div id="page_container">
 
        <?php include("overall_header.html"); ?> 
 
        <div id="inner_content">
            <div id="inner_container">
                <div id="inner_top">
                    <div id="feature">
 
 
<?php
if (isset($_POST['Submit']))
    {
   // we'll begin by assigning the To address and message subject 
   $to="example@gmail.com"; 
   $subject="New Home Advert"; 
   $fromname=stripslashes($_POST['fromname']);
   $fromemail=stripslashes($_POST['fromemail']);
   $telNo=stripslashes($_POST['landline']);
   $mobile=stripslashes($_POST['mobile']);
   $address=stripslashes($_POST['address1']);
   $rent=stripslashes($_POST['rent']);
   $postCode=stripslashes($_POST['postcode']);
 
   // get the sender's name and email address 
   // we'll just plug them a variable to be used later 
   $from = $fromname."<".$fromemail.">"; 
 
 
 
 
 
 
function checkUKTelephone (&$strTelephoneNumber, &$intError, &$strError) {
  
  // Copy the parameter and strip out the spaces
  $strTelephoneNumberCopy = str_replace (' ', '', $strTelephoneNumber);
 
  // Convert into a string and check that we were provided with something
  if (empty($strTelephoneNumberCopy)) {
    $intError = 1;
    $strError = 'Telephone number not provided';
    return false;
  }
  
  // Don't allow country codes to be included (assumes a leading "+") 
  if (ereg('^(\+)[\s]*(.*)$',$strTelephoneNumberCopy)) {
    $intError = 2;
    $strError = 'UK telephone number without the country code, please';
    return false;
  }
  
  // Remove hyphens - they are not part of a telephine number
  $strTelephoneNumberCopy = str_replace ('-', '', $strTelephoneNumberCopy);
  
  // Now check that all the characters are digits
  if (!ereg('^[0-9]{10,11}$',$strTelephoneNumberCopy)) {
    $intError = 3;
    $strError = 'UK telephone numbers should contain 10 or 11 digits';
    return false;
  }
  
  // Now check that the first digit is 0
  if (!ereg('^0[0-9]{9,10}$',$strTelephoneNumberCopy)) {
    $intError = 4;
    $strError = 'The telephone number should start with a 0';
    return false;
  }        
  
  // Check the string against the numbers allocated for dramas
  
  // Expression for numbers allocated to dramas
    
    $tnexp[0] =  '^(0113|0114|0115|0116|0117|0118|0121|0131|0141|0151|0161)(4960)[0-9]{3}$';
    $tnexp[1] =  '^02079460[0-9]{3}$';
    $tnexp[2] =  '^01914980[0-9]{3}$';
    $tnexp[3] =  '^02890180[0-9]{3}$';
    $tnexp[4] =  '^02920180[0-9]{3}$';
    $tnexp[5] =  '^01632960[0-9]{3}$';
    $tnexp[6] =  '^07700900[0-9]{3}$';
    $tnexp[7] =  '^08081570[0-9]{3}$';
    $tnexp[8] =  '^09098790[0-9]{3}$';
    $tnexp[9] =  '^03069990[0-9]{3}$';
    
  foreach ($tnexp as $regexp) {  
    if (ereg($regexp,$strTelephoneNumberCopy, $matches)) {
      $intError = 5;
      $strError = 'The telephone number is either invalid or inappropriate';
      return false;
    }
  }
  
  // Finally, check that the telephone number is appropriate.
  if (!ereg('^(01|02|03|05|070|071|072|073|074|075|07624|077|078|079)[0-9]+$',$strTelephoneNumberCopy)) {
    $intError = 5;
    $strError = 'The telephone number is either invalid or inappropriate';
    return false;
  }
  
  // Seems to be valid - return the stripped telephone number
  $strTelephoneNumberCopy = $strTelephoneNumberCopy;
  $intError = 0;
  $strError = '';
  return true;  
}
 
 
function checkPostcode (&$toCheck) {
 
  // Permitted letters depend upon their position in the postcode.
  $alpha1 = "[abcdefghijklmnoprstuwyz]";                          // Character 1
  $alpha2 = "[abcdefghklmnopqrstuvwxy]";                          // Character 2
  $alpha3 = "[abcdefghjkstuw]";                                   // Character 3
  $alpha4 = "[abehmnprvwxy]";                                     // Character 4
  $alpha5 = "[abdefghjlnpqrstuwxyz]";                             // Character 5
  
  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA with a space
  $pcexp[0] = '^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$';
 
  // Expression for postcodes: ANA NAA
  $pcexp[1] =  '^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$';
 
  // Expression for postcodes: AANA NAA
  $pcexp[2] =  '^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$';
  
  // Exception for the special postcode GIR 0AA
  $pcexp[3] =  '^(gir)(0aa)$';
  
  // Standard BFPO numbers
  $pcexp[4] = '^(bfpo)([0-9]{1,4})$';
  
  // c/o BFPO numbers
  $pcexp[5] = '^(bfpo)(c\/o[0-9]{1,3})$';
  
  // Overseas Territories
  $pcexp[6] = '^([a-z]{4})(1zz)$/i';
 
  // Load up the string to check, converting into lowercase
  $postcode = strtolower($toCheck);
 
  // Assume we are not going to find a valid postcode
  $valid = false;
  
  // Check the string against the six types of postcodes
  foreach ($pcexp as $regexp) {
  
    if (ereg($regexp,$postcode, $matches)) {
            
      // Load new postcode back into the form element  
          $postcode = strtoupper ($matches[1] . ' ' . $matches [3]);
            
      // Take account of the special BFPO c/o format
      $postcode = ereg_replace ('C\/O', 'c/o ', $postcode);
      
      // Remember that we have found that the code is valid and break from loop
      $valid = true;
      break;
    }
  }
    
  // Return with the reformatted valid postcode in uppercase if the postcode was 
  // valid
  if ($valid){
      $toCheck = $postcode; 
        return true;
    } 
    else return false;
}  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
   // Check for a username 
   if($fromname=='') // If no input on fromname textbox  
        echo '<p><strong>Name</strong> field is mandatory.</p>'; 
    if($fromemail==''||!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $fromemail))
        echo '<p><strong>Email address</strong> is invalid.</p>';
    if (!checkUKTelephone ($telNo, $errorNo, $errorText) )
      echo "<p><strong>{$errorText}</strong></p>";
     if($mobile=='')
    echo '<p><strong>Invalid Mobile Number</strong></p>';
    if($address=='')
        echo '<p><strong>Address</strong> field is mandatory.</p>';
    if (!checkPostcode ($postcode) )
      echo '<p><strong>Invalid postcode. </strong></p>';
    if($rent=='')
        echo '<p><strong>Rent</strong> field is mandatory</p>';
    
 
   // generate a random string to be used as the boundary marker 
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x"; 
 
   // now we'll build the message headers 
   $headers = "From: $from\r\n" . 
   "MIME-Version: 1.0\r\n" . 
      "Content-Type: multipart/mixed;\r\n" . 
      " boundary=\"{$mime_boundary}\""; 
 
   // here, we'll start the message body. 
   // this is the text that will be displayed 
   // in the e-mail 
   $message=stripslashes($_POST['fromname'])."This is an example"; 
 
   // next, we'll build the invisible portion of the message body 
   // note that we insert two dashes in front of the MIME boundary  
   // when we use it 
   $message = "This is a multi-part message in MIME format.\n\n" . 
      "--{$mime_boundary}\n" . 
      "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . 
      "Content-Transfer-Encoding: 7bit\n\n" . 
   $message . "\n\n"; 
 
   // now we'll process our uploaded files 
   foreach($_FILES as $userfile){ 
      // store the file information to variables for easier access 
      $tmp_name = $userfile['tmp_name']; 
      $type = $userfile['type']; 
      $name = $userfile['name']; 
      $size = $userfile['size']; 
 
      // if the upload succeded, the file will exist 
      if (file_exists($tmp_name)){ 
 
         // check to make sure that it is an uploaded file and not a system file 
         if(is_uploaded_file($tmp_name)){ 
      
            // open the file for a binary read 
            $file = fopen($tmp_name,'rb'); 
      
            // read the file content into a variable 
            $data = fread($file,filesize($tmp_name)); 
 
            // close the file 
            fclose($file); 
      
            // now we encode it and split it into acceptable length lines 
            $data = chunk_split(base64_encode($data)); 
         } 
      
         // now we'll insert a boundary to indicate we're starting the attachment 
         // we have to specify the content type, file name, and disposition as 
         // an attachment, then add the file content. 
         // NOTE: we don't set another boundary to indicate that the end of the  
         // file has been reached here. we only want one boundary between each file 
         // we'll add the final one after the loop finishes. 
         $message .= "--{$mime_boundary}\n" . 
            "Content-Type: {$type};\n" . 
            " name=\"{$name}\"\n" . 
            "Content-Disposition: attachment;\n" . 
            " filename=\"{$fileatt_name}\"\n" . 
            "Content-Transfer-Encoding: base64\n\n" . 
         $data . "\n\n"; 
      } 
   } 
   // here's our closing mime boundary that indicates the last of the message 
   $message.="--{$mime_boundary}--\n"; 
   // now we just send the message 
   if (@mail($to, $subject, $message, $headers)) 
      echo "<strong style='color:#f00';>Message sent</strong>";  
   else 
      echo "<strong style='color:#f00';>Failed to send</strong>"; 
}
 
 
 else { 
?>  
 
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1" onsubmit="return validate()">
<table>
                    <tr>
                        <td colspan="5">
                            <label class="form_title">Contact Information:</label>
                        </td>
                    </tr>
                    <tr>
                        <td>                
                            <label class="searchtext">Name:</label>     
                        </td>
                        <td colspan="4">
                            <input type="text" name="fromname">
                        </td>
                    </tr>
                    <tr>
                        <td>                
                            <label class="searchtext">Email:</label>    
                        </td>
                        <td colspan="4">
                            <input type="text" name="fromemail">
                        </td>
                    </tr>
                    <tr>
                        <td>                
                            <label class="searchtext">Phone:</label>    
                        </td>
                        <td colspan="4">
                            <input type="text" name="landline">
                        </td>
                    </tr>
                    <tr>
                        <td>                
                            <label class="searchtext">Mobile:</label>   
                        </td>
                        <td colspan="4">
                            <input type="text" name="mobile">
                        </td>
                    </tr>
                        
                                        
 
 
 
 
                    <tr>
                        <td colspan="5">
                            <label class="form_title">Advertise your home:</label>
                        </td>
                    </tr>
 
 
                    <tr>
                        <td>
                            <label class="searchtext">Address Line 1:</label>
                        </td>
                        <td colspan="4">
                                <input type="text" value="" name="address1">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label class="searchtext">Address Line 2:</label>
                        </td>
                        <td colspan="4">
                                <input type="text" value="" name="address2">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label class="searchtext">Town:</label>
                        </td>
                        <td colspan="4">
                                <input type="text" value="" name="town">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label class="searchtext">Post Code:</label>
                        </td>
                        <td colspan="4">
                                <input type="text" value="" name="postcode">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label class="searchtext">Bedrooms:</label>
                        </td>
                        <td colspan="4">
                                <select class="searchlist_long" name="bedrooms">
                                    <option value="- 1" selected>Please Select...</option>
                                    <option value="">--------------------</option>
                                    <option value="1">One Bedroom</option>
                                    <option value="2">Two Bedroom</option>
                                    <option value="3">Three Bedroom</option>
                                    <option value="4">Four Bedroom</option>
                                    <option value="5">Five Bedroom</option>
                                    <option value="6">More...</option>
                                </select>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label class="searchtext">Furnishing:</label>
                        </td>
                        <td colspan="4">
                                <select class="searchlist_long" name="furnish">
                                    <option value="- 1" selected>Please Select...</option>
                                    <option value="">--------------------</option>
                                    <option value="1">Unfurnihed</option>
                                    <option value="2">Part Furnished</option>
                                    <option value="3">Fully Furnished</option>
                                </select>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label class="searchtext">Rent:</label>
                        </td>
                        <td colspan="4">
                                <input type="text" value="" name="rent">
                        </td>
                    </tr>
 
 
 
                    <tr>
                        <td>
                            <label class="searchtext">Description:</label>
                        </td>
                        <td colspan="4">
                                <textarea cols="60" rows="5" type="text" value="" name="description"></textarea>
                        </td>
                    </tr>
 
 
 
                    <tr>
                        <td colspan="5">
                            <label class="form_title">Upload Images:</label>
                        </td>
                    </tr>
                    <tr>
                        <td>                
                            <label class="searchtext">Main Image:</label>   
                        </td>
                        <td colspan="4">
                            <input type="file" name="file1">
                        </td>
                    </tr>
                    <tr>
                        <td>                
                            <label class="searchtext">Image 2:</label>  
                        </td>
                        <td colspan="4">
                            <input type="file" name="file2">
                        </td>
                    </tr>
                    <tr>
                        <td>                
                            <label class="searchtext">Image 3:</label>  
                        </td>
                        <td colspan="4">
                            <input type="file" name="file3">
                        </td>
                    </tr>
                    <tr>
                        <td>                
                            <label class="searchtext">Image 4:</label>  
                        </td>
                        <td colspan="4">
                            <input type="file" name="file4">
                        </td>
                    </tr>
 
 
 
 
 
                                
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td><input type="submit" name="Submit" value="Submit" /></td>
                    </tr>
 
 
                </table>
 
 
 
</form>
 
 
<?php } ?> 
                    </div>
                    <div id="search">
                        <h3>How to ... ?</h3>
                        <p>To place your property on our site please fill in the form to your right and pay the invoice fee, once payment has cleared on our side your house will be listed until it is let, and will remain on the site until you notify us otherwise.</p>
                        <hr />
                        <h3>Search from list...</h3>
 
        <?php include("jump.php"); ?>       
                        
                        <hr />
                        <p>Join Fife's newest and most innovative rental market site today and 
                        enjoy free listings*</p>
                        
                        <p>(* = Limited time only)
                    </div>
                </div>
                <div id="inner_bottom">
                    <div id="premium"></div>
                </div>
            </div>
        
        
        </div>
 
 
        <?php include("overall_footer.html"); ?> 
 
 
        
    </div>
 
 
</body>
 
</html>
 
User avatar
Kadanis
Forum Contributor
Posts: 180
Joined: Tue Jun 20, 2006 8:55 am
Location: Dorset, UK
Contact:

Re: PHP email script

Post by Kadanis »

First off you may want to look at javascript validation to highlight fails especially for the image size otherwise you will have to upload the image in php before you can validate and that could clog up your server/users bandwidth, but if you are using server side validation only the way i would do it is something like this (very basic example)

Code: Select all

 
<?php
//initialise vars
$image = '';
$error = '';
$uploadLocation = '/path/to/image/directory/on/server/';
//get form fields
$field = (isset($_POST['field'])) ? $_POST['field'] : '';
$submit = (isset($_POST['submit'])) ? $_POST['submit'] : 'false';
 
//if submitted then process email
if ($submit == 'true'){
    //validate image size in tmp location on server
    $tmp_image = $_FILES['image']['tmp_name'];  
    list($width, $height, $itype, $attr) = getimagesize($tmp_image);
    if ($width <= 250 && $height <= 160){
        //move image to storage
        if (move_uploaded_files($_FILES['image']['tmp_name'], $uploadLocation)) {
            //continue with email processing
        } else {
            $error = 'Failed to upload file.';
        }    
    } else {
        $error = 'Image Dimensions Exceed Allowed Limits. Images must not be larger than 250 x 160';
    }
}
?>
<html>
<body>
<form name="contactUs" method="post" action="<?php echo basename(__FILE__); ?>" enctype="multipart/form-data">
<input type="hidden" name="submit" value="true" />
<label for="field">
<?php if ($field == ''): ?>
    <span style="color:red;">Field Name</span>
<?php else: ?>
    Field Name
<?php endif; ?>
</label>
<input type="text" name="field" value="<?php echo $field;?>" />
 
<label for="image">
<?php if ($image== ''): ?>
    <span style="color:red;">Image</span>
<?php else: ?>
    Image
<?php endif; ?>
</label>
<input type="file" name="image" value="" />
 
<input type="submit" value="submit" />
</form>
<?php if ($error != ''){echo $error;}?>
 
</body>
</html>
 
This does everything apart from sending the email, which I recommend you look at Swiftmailer (forums on this site, or at http://www.swiftmailer.org/)

The example above has only 1 field to validate and it is server side, you could add javascript as well if you wanted.

Hope this helps
Andorphin
Forum Newbie
Posts: 7
Joined: Fri Oct 31, 2008 3:44 am

Re: PHP email script

Post by Andorphin »

Hey Thanks for the tip, i have javascript validation for everything else as it is but I took it out to see how to do it in PHP only.

How would I integrate this script into my current file, so it sends in an email?

I am very inexperienced at PHP, and thank again.

I don't know if their is any developers kind enough to build me the entire script for free...I have been trying to build this site for 6 months myself and I still can't get past this section.

Many Thanks
Andorphin
Forum Newbie
Posts: 7
Joined: Fri Oct 31, 2008 3:44 am

Re: PHP email script

Post by Andorphin »

any takers........please?
bmoyles0117
Forum Newbie
Posts: 22
Joined: Sun Nov 02, 2008 1:46 am

Re: PHP email script

Post by bmoyles0117 »

You still have a little bit of work to do. But here's about an hour of my work fixing out kinks and stuff and making it much more efficient.

You must replace example@gmail.com with your email in the code.

Code: Select all

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
    <head>
        <title>Rent in Fife</title>
        <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
        <meta http-equiv="Content-Language" content="en-us" />
        <meta http-equiv="imagetoolbar" content="no" />
        <meta name="MSSmartTagsPreventParsing" content="true" />
        <meta name="description" content="Description" />
        <meta name="keywords" content="Keywords" />
        <meta name="author" content="Colin Burt" />
        <style type="text/css" media="all">@import "includes/stylesheets/default.css";</style>
        <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA55lo0C46TQhEnHj8DQBTtxTaQ5dQGm2LYPeImFe76gdZiHRAAxSDRuKZPK91669NrlMj5ollP4Hp3Q" type="text/javascript"></script>
        <script src="includes/javascript/map_search.js" type="text/javascript"></script>
    </head>
    <body onload="Load()" onunload="GUnload()">
        <!-- Page body container starts here -->
        <div id="page_container">
            <?php include 'overall_header.html'; ?>
            <div id="inner_content">
                <div id="inner_container">
                    <div id="inner_top">
                        <div id="feature">
<?php
function clean($var) {
    return strip_tags(htmlentities(stripslashes($var)));
}
 
function checkUKTelephone (&$strTelephoneNumber) {
    // Copy the parameter and strip out the spaces
    $info = new stdClass;
    $info->phoneno = str_replace (' ', '', $strTelephoneNumber);
 
    // Convert into a string and check that we were provided with something
    if(empty($info->phoneno))
        return 'error1';
 
    // Don't allow country codes to be included (assumes a leading "+")
    if(ereg('^(\+)[\s]*(.*)$',$info->phoneno))
        return 'error2';
 
    // Remove hyphens - they are not part of a telephine number
    $info->phoneno = str_replace ('-', '', $info->phoneno);
 
    // Now check that all the characters are digits
    if(!ereg('^[0-9]{10,11}$',$info->phoneno))
        return 'error3';
 
    // Now check that the first digit is 0
    if (!ereg('^0[0-9]{9,10}$',$info->phoneno))
        return 'error4';
 
    // Check the string against the numbers allocated for dramas
    // Expression for numbers allocated to dramas
    $tnexp[0] =  '^(0113|0114|0115|0116|0117|0118|0121|0131|0141|0151|0161)(4960)[0-9]{3}$';
    $tnexp[1] =  '^02079460[0-9]{3}$';
    $tnexp[2] =  '^01914980[0-9]{3}$';
    $tnexp[3] =  '^02890180[0-9]{3}$';
    $tnexp[4] =  '^02920180[0-9]{3}$';
    $tnexp[5] =  '^01632960[0-9]{3}$';
    $tnexp[6] =  '^07700900[0-9]{3}$';
    $tnexp[7] =  '^08081570[0-9]{3}$';
    $tnexp[8] =  '^09098790[0-9]{3}$';
    $tnexp[9] =  '^03069990[0-9]{3}$';
    foreach($tnexp as $regexp)
        if(ereg($regexp, $info->phoneno, $matches))
            return 'error5';
 
    // Finally, check that the telephone number is appropriate.
    if(!ereg('^(01|02|03|05|070|071|072|073|074|075|07624|077|078|079)[0-9]+$',$info->phoneno))
        return 'error5';
 
    // Seems to be valid - return the stripped telephone number
    return true;  
}
 
function checkPostcode (&$toCheck) {
    // Permitted letters depend upon their position in the postcode.
    $alpha1 = "[abcdefghijklmnoprstuwyz]";                          // Character 1
    $alpha2 = "[abcdefghklmnopqrstuvwxy]";                          // Character 2
    $alpha3 = "[abcdefghjkstuw]";                                   // Character 3
    $alpha4 = "[abehmnprvwxy]";                                     // Character 4
    $alpha5 = "[abdefghjlnpqrstuwxyz]";                             // Character 5
 
    // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA with a space
    $pcexp[0] = '^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$';
    // Expression for postcodes: ANA NAA
    $pcexp[1] =  '^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$';
    // Expression for postcodes: AANA NAA
    $pcexp[2] =  '^('.$alpha1.'{1}'.$alpha2.'[0-9]{1}'.$alpha4.')([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$';
    // Exception for the special postcode GIR 0AA
    $pcexp[3] =  '^(gir)(0aa)$';
    // Standard BFPO numbers
    $pcexp[4] = '^(bfpo)([0-9]{1,4})$';
    // c/o BFPO numbers
    $pcexp[5] = '^(bfpo)(c\/o[0-9]{1,3})$';
    // Overseas Territories
    $pcexp[6] = '^([a-z]{4})(1zz)$/i';
    // Load up the string to check, converting into lowercase
    $postcode = strtolower($toCheck);
    // Assume we are not going to find a valid postcode
    $valid = false;
 
    // Check the string against the six types of postcodes
    foreach($pcexp as $regexp) {
        if(ereg($regexp,$postcode, $matches)) {
            // Load new postcode back into the form element  
            $postcode = strtoupper($matches[1] . ' ' . $matches [3]);
            // Take account of the special BFPO c/o format
            $postcode = ereg_replace('C\/O', 'c/o ', $postcode);
            // Remember that we have found that the code is valid and break from loop
            $valid = true;
            break;
        }
    }
    // Return with the reformatted valid postcode in uppercase if the postcode was valid
    return $valid;
}  
 
if(isset($_POST['Submit'])) {
    $form = new stdClass;
    $form->to = "example@gmail.com";
    $form->subject = "New Home Advert";
    foreach($_POST as $key => $value)
        $form->$key = clean($value);
 
    $form->from = "{$form->fromname} <{$form->fromemail}>";
 
    $errors = array(
        'error1'    => 'Telephone number not provided',
        'error2'    => 'UK Telephone number without the country code please',
        'error3'    => 'UK telephone numbers should contain 10 or 11 digits',
        'error4'    => 'The telephone number should start with a 0',
        'error5'    => 'The telephone number is either invalid or inappropriate'
    ); 
 
    // Check for a username
    $postcodeCheck = checkPostcode($form->postcode);
    $phonenoCheck = checkUKTelephone($form->landline);
    if(empty($form->fromname))
        echo '<p><strong>Name</strong> field is mandatory.</p>';
    if((empty($form->fromemail)) || (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $form->fromemail)))
        echo '<p><strong>Email address</strong> is invalid.</p>';
    if($phonenoCheck != true)
        echo "<p><strong>{$errors[$phonenoCheck]}</strong></p>";
    if(empty($form->mobile))
        echo '<p><strong>Invalid Mobile Number</strong></p>';
    if(empty($form->address1))
        echo '<p><strong>Address</strong> field is mandatory.</p>';
    if(!checkPostcode($form->postcode))
        echo '<p><strong>Invalid postcode. </strong></p>';
    if(empty($rent))
        echo '<p><strong>Rent</strong> field is mandatory</p>';
   
    $mail = new stdClass;
    // generate a random string to be used as the boundary marker
    $mail->mime_boundary = "==Multipart_Boundary_x" . md5(mt_rand()) . "x";
   
    // now we'll build the message headers
    $mail->headers = "From: {$form->from}\r\n"
        . "MIME-Version: 1.0\r\n"
        . "Content-Type: multipart/mixed;\r\n"
        . " boundary=\"{$mail->mime_boundary}\"";
    
    // here, we'll start the message body. this is the text that will be displayed in the e-mail
    $mail->message = "{$form->fromname} This is an example";
 
    // next, we'll build the invisible portion of the message body note that we insert two dashes in front of the MIME boundary when we use it
    $mail->message = "This is a multi-part message in MIME format.\n\n"
        . "--{$mail->mime_boundary}\n"
        . "Content-Type: text/plain; charset=\"iso-8859-1\"\n"
        . "Content-Transfer-Encoding: 7bit\n\n"
        . $mail->message
        . "\n\n";
 
    // now we'll process our uploaded files
    $fileInfo = new stdClass;
    foreach($_FILES as $userfile) {
        // store the file information to variables for easier access
        $fileInfo->tmp_name = $userfile['tmp_name'];
        $fileInfo->type = $userfile['type'];
        $fileInfo->name = $userfile['name'];
        $fileInfo->size = $userfile['size'];
 
        // if the upload succeded, the file will exist
        if(file_exists($fileInfo->tmp_name)) {
         
            // check to make sure that it is an uploaded file and not a system file
            if(is_uploaded_file($fileInfo->tmp_name)){
                // open the file for a binary read
                $file = fopen($fileInfo->tmp_name,'rb');
                // read the file content into a variable
                $data = fread($file,filesize($fileInfo->tmp_name));
                // close the file
                fclose($file);
                // now we encode it and split it into acceptable length lines
                $data = chunk_split(base64_encode($data));
            }
    
            /**
             * now we'll insert a boundary to indicate we're starting the attachment
             * we have to specify the content type, file name, and disposition as
             * an attachment, then add the file content.
             * NOTE: we don't set another boundary to indicate that the end of the  
             * file has been reached here. we only want one boundary between each file
             * we'll add the final one after the loop finishes.
             */
            $mail->message .= "--{$mail->mime_boundary}\n"
                . "Content-Type: {$fileInfo->type};\n"
                . " name=\"{$fileInfo->name}\"\n"
                . "Content-Disposition: attachment;\n"
                . " filename=\"{$userfile['name']}\"\n"
                . "Content-Transfer-Encoding: base64\n\n"
                . $data
                . "\n\n";
        }
    }
    
    // here's our closing mime boundary that indicates the last of the message
    $mail->message .= "--{$mail->mime_boundary}--\n";
    // now we just send the message
    if(mail($form->to, $form->subject, $mail->message, $mail->headers))
        echo '<strong style="color:#f00;">Message sent</strong>';  
    else
        echo '<strong style="color:#f00;">Failed to send</strong>';
} else {
?>  
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1" onsubmit="return validate()">
    <table>
        <tr>
            <td colspan="5">
                <label class="form_title">Contact Information:</label>
            </td>
        </tr>
        <tr>
            <td>               
                <label class="searchtext">Name:</label>    
            </td>
            <td colspan="4">
                <input type="text" name="fromname" />
            </td>
        </tr>
        <tr>
            <td>               
                <label class="searchtext">Email:</label>    
            </td>
            <td colspan="4">
                <input type="text" name="fromemail" />
            </td>
        </tr>
        <tr>
            <td>               
                <label class="searchtext">Phone:</label>    
            </td>
            <td colspan="4">
                <input type="text" name="landline" />
            </td>
        </tr>
        <tr>
            <td>               
                <label class="searchtext">Mobile:</label>  
            </td>
            <td colspan="4">
                <input type="text" name="mobile" />
            </td>
        </tr>
        <tr>
            <td colspan="5">
                <label class="form_title">Advertise your home:</label>
            </td>
        </tr>
        <tr>
            <td>
                <label class="searchtext">Address Line 1:</label>
            </td>
            <td colspan="4">
                <input type="text" value="" name="address1" />
            </td>
        </tr>
        <tr>
            <td>
                <label class="searchtext">Address Line 2:</label>
            </td>
            <td colspan="4">
                <input type="text" value="" name="address2" />
            </td>
        </tr>
        <tr>
            <td>
                <label class="searchtext">Town:</label>
            </td>
            <td colspan="4">
                <input type="text" value="" name="town" />
            </td>
        </tr>
        <tr>
            <td>
                <label class="searchtext">Post Code:</label>
            </td>
            <td colspan="4">
                <input type="text" value="" name="postcode" />
            </td>
        </tr>
        <tr>
            <td>
                <label class="searchtext">Bedrooms:</label>
            </td>
            <td colspan="4">
                <select class="searchlist_long" name="bedrooms">
                    <option value="- 1" selected>Please Select...</option>
                    <option value="">--------------------</option>
                    <option value="1">One Bedroom</option>
                    <option value="2">Two Bedroom</option>
                    <option value="3">Three Bedroom</option>
                    <option value="4">Four Bedroom</option>
                    <option value="5">Five Bedroom</option>
                    <option value="6">More...</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <label class="searchtext">Furnishing:</label>
            </td>
            <td colspan="4">
                <select class="searchlist_long" name="furnish">
                    <option value="- 1" selected>Please Select...</option>
                    <option value="">--------------------</option>
                    <option value="1">Unfurnished</option>
                    <option value="2">Part Furnished</option>
                    <option value="3">Fully Furnished</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <label class="searchtext">Rent:</label>
            </td>
            <td colspan="4">
                <input type="text" value="" name="rent" />
            </td>
        </tr>
        <tr>
            <td>
                <label class="searchtext">Description:</label>
            </td>
            <td colspan="4">
                <textarea cols="60" rows="5" type="text" value="" name="description"></textarea>
            </td>
        </tr>
        <tr>
            <td colspan="5">
                <label class="form_title">Upload Images:</label>
            </td>
        </tr>
        <tr>
            <td>               
                <label class="searchtext">Main Image:</label>  
            </td>
            <td colspan="4">
                <input type="file" name="file1" />
            </td>
        </tr>
        <tr>
            <td>               
                <label class="searchtext">Image 2:</label>  
            </td>
            <td colspan="4">
                <input type="file" name="file2" />
            </td>
        </tr>
        <tr>
            <td>               
                <label class="searchtext">Image 3:</label>  
            </td>
            <td colspan="4">
                <input type="file" name="file3" />
            </td>
        </tr>
        <tr>
            <td>               
                <label class="searchtext">Image 4:</label>  
            </td>
            <td colspan="4">
                <input type="file" name="file4" />
            </td>
        </tr>
        <tr>
            <td colspan="4">&nbsp;</td>
            <td><input type="submit" name="Submit" value="Submit" /></td>
        </tr>
    </table>
</form>
<?php } ?>
</div>
<div id="search">
    <h3>How to ... ?</h3>
    <p>
        To place your property on our site please fill in the form to your 
        right and pay the invoice fee, once payment has cleared on our side 
        your house will be listed until it is let, and will remain on the 
        site until you notify us otherwise.
    </p>
    <hr />
    <h3>Search from list...</h3>
    <?php include 'jump.php'; ?>      
    <hr />
    <p>
        Join Fife's newest and most innovative rental market site today and
        enjoy free listings*
    </p>
    <p>(* = Limited time only)</p>
</div>
</div>
<div id="inner_bottom">
    <div id="premium"></div>
    </div>
</div>
</div>
<?php include 'overall_footer.html'; ?>
</div>
</body>
</html>
 
Post Reply