SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2007
    Location
    United Kingdom
    Posts
    83
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Can someone help me to set up this script?

    I need to get a form to e-mail script modified to suit my form, but I don't know which parts of the script to change or how to change them. I started trying to learn PHP a couple of months ago, but I'm really struggling to get beyond the most basic principles.

    Could some expert look at this and tell me (a) exactly which parts to modify and (b) what to add/change in them?

    The form is:
    HTML Code:
    <div id="form">
    <form method="post" action="askform.php">
    
    <p><label for="title">Title:</label></p>
    <p><select name="title" id="title">
    <option value="Mr.">Mr.</option>
    <option value="Mrs.">Mrs.</option>
    <option value="Miss">Miss</option>
    <option value="Ms.">Ms.</option>
    </select></p>
    
    <p><label for="firstname">First name:</label></p>
    <p><input type="text" id="firstname" name="firstname" value="" size="33" maxlength="33"/></p>
    
    <p><label for="surname">Surname:</label></p>
    <p><input type="text" id="surname" name="surname" value="" size="33" maxlength="33"/></p>
    
    <p><label for="email">E-mail address:</label></p>
    <p><input type="text" id="email" name="email" value="" size="33" maxlength="55"/></p>
    
    <p><label for="daytel">Daytime telephone no:</label></p>
    <p><input type="text" id="daytel" name="daytel" value="" size="33" maxlength="33"/></p>
    
    <p><label for="evetel">Evening telephone no:</label></p>
    <p><input type="text" id="evetel" name="evetel" value="" size="33" maxlength="33"/></p>
    
    <p><label for="preference">When is the best time to contact you?</label></p>
    <div id="nopadding">
    <p><input type="radio" id="preference" name="preference" value="daytime"/><label>Daytime </label><input type="radio" name="preference" value="evening"/><label>Evening</label></p>
    </div>
    
    <p><label for="dropdown1">Type of service required:</label></p>
    <p><select name="dropdown1" id="dropdown1">
    <option value="Domestic">Domestic</option>
    <option value="Commercial">Commercial</option>
    </select></p>
    
    <p><label for="dropdown2">Will the work be inside, outside, or both?</label></p>
    <p><select name="dropdown2" id="dropdown2">
    <option value="Interior">Interior</option>
    <option value="Exterior">Exterior</option>
    <option value="Interior and exterior">Both</option></select></p>
    
    <p><label for="message">Your message or query:</label></p>
    <p><textarea name="message" id="message" rows="7" cols="66"></textarea></p>
    
    <p><input type="submit" name="submit" value="Send Message"/></p>
    
    </form>
    </div>
    And the script is taken directly from phpmailer-fe:
    Code:
    <?php
    define("VERSION", "3.0.1");
    
    define("FEPATH", getcwd() . substr($_SERVER['PHP_SELF'],0,1) );
    
    $fileBanlist = FEPATH . 'banlog.php';
    
    $useBanlist  = false;
    if ( is_writable($fileBanlist) ) {
      $useBanlist  = true;
    }
    
    $redirectOnBan  = "http://" . $_SERVER['HTTP_HOST'];
    
    $useWindowClose = false;
    
    foreach ($_POST as $key => $value) {
      $key   = strtolower($key);
      $value = str_replace("\n","<br />",$value);
      if (!is_array($value)) {
        $$key = trim(utf8_urldecode($value));
      }
      if ($useBanlist && is_writable($fileBanlist)) {
        if ( !stristr($key, 'url') ) { // will only search if 'url' not found in $key
          $hacked = FALSE;
          $hacked = checkBannedInput($key,$value,$fileBanlist);
        }
      }
      if ( $hacked === TRUE ) {
        echo "Comments were not sent ...<br />";
        echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"10; URL=" . $redirectOnBan . "\">";
        if ($useWindowClose) {
          echo '<script language="javascript" type="text/javascript">' . "\n";
          echo 'setTimeout("self.close()", 5000 )' . "\n";
          echo '</script>' . "\n";
        }
        exit();
      }
    }
    
    $loadDefault = FEPATH . 'default.config.php';
    if (file_exists($loadDefault)) {
      include_once( $loadDefault );
      foreach ($_POST as $key => $value) {
        $key   = strtolower($key);
        $value = str_replace("\n","<br />",$value);
        $$key  = trim(utf8_urldecode($value));
      }
    }
    if ( getenv('HTTP_REFERER') != '' || $_POST['referer'] != '' ) {
      if ( getenv('HTTP_REFERER') != '' ) {
        $path_parts = pathinfo(getenv('HTTP_REFERER'));
      } else {
        $path_parts = pathinfo(trim($_POST["referer"]));
      }
      $filearr = split("\.",$path_parts["basename"]);
      if (count($filearr) > 1) {
        $loadFile = '';
        for ($i=0;$i<count($filearr)-1;$i++) {
          $loadFile .= $filearr[$i] . ".";
        }
        $loadFile .= 'config.php';
      }
      $loadFile = FEPATH . $loadFile;
      if ( file_exists($loadFile) ) {
        include_once( $loadFile );
      }
      foreach ($_POST as $key => $value) {
        $key   = strtolower($key);
        $value = str_replace("\n","<br />",$value);
        $$key  = trim(utf8_urldecode($value));
      }
    }
    $loadDefault = '';
    $loadFile    = '';
    
    $fixedFromEmail = ''; //'webmaster@thisdomain.com';
    $fixedFromName  = ''; //'Webmaster'
    
    if (!$email_bad_array) {
      $email_bad_array = "\r|\n|to:|cc:|bcc:";
    }
    
    if (!$recipient) {
      $recipient = 'webmaster@yourdomain.com';
    } else {
      $recipient = eregi_replace($email_bad_array,'',$recipient);
      $recipient = str_replace(" ", "", $recipient);
    }
    
    if (!$cc) {
      $cc = "";
    } else {
      $cc = eregi_replace($email_bad_array,'',$cc);
      $cc = str_replace(";", ",", $cc);
      $cc = str_replace(" ", "", $cc);
    }
    
    if (!$bcc) {
      $bcc = '';
    } else {
      $bcc = eregi_replace($email_bad_array,'',$bcc);
      $bcc = str_replace(";", ",", $bcc);
      $bcc = str_replace(" ", "", $bcc);
    }
    
    if (!$subject) {
      $subject = 'Form Submission' . ' from: ' . $_SERVER['HTTP_HOST'];
    } else {
      $subject = eregi_replace($email_bad_array,'',$subject);
      $subject = stripslashes($subject);
    }
    
    if (!$env_report) {
      $env_report = array ();
      //$env_report = array ('REMOTE_HOST','REMOTE_USER','REMOTE_ADDR','HTTP_USER_AGENT','HTTP_REFERER');
    }
    
    if (!$allowedFileTypes) {
      $allowedFileTypes = "doc|xls|pdf|jpg|jpeg|png|gif|zip|rar|gz";
    }
    
    if (!$redirectOnFail) {
      $redirectOnFail  = '';
    }
    
    if (!$replyEmailOnSuccess) {
      $replyEmailOnSuccess  = '';
    }
    
    if (!$replyEmailOnFail) {
      $replyEmailOnFail  = '';
    }
    
    if (!$useAsAutoResponder) {
      $useAsAutoResponder = false;
    }
    
    $useWorxTuring = false;
    
    $PHPMailerLocation = FEPATH . "class.phpmailer.php";
    
    // $referers   = array ($_SERVER['HTTP_HOST']);
    $referers   = array ();
    
    $useEnvRpt  = false;
    
    $bannedEmails    = ''; //array ('*@anydomain.com', '*@otherdomain.com');
    
    define("SEPARATOR", ($separator)?$separator:": ");
    
    define("NEWLINE", ($newline)?$newline:"\n");
    
    define("DELIMITERLEFT", "{");
    
    define("DELIMITERRIGHT", "}");
    
    // do the Worx Turing test
    if ( $useWorxTuring && isset($_POST["WorxTuringTest"]) ) {
      session_start();
      if (strtoupper($_POST["WorxTuringTest"]) != $_SESSION['WorxTuringTest']) {
        echo "Security test failed ...<br />";
        echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"4; URL=" . $redirectOnBan . "\">";
        if ($useWindowClose) {
          echo '<script language="javascript" type="text/javascript">' . "\n";
          echo 'setTimeout("self.close()", 5000 )' . "\n";
          echo '</script>' . "\n";
        }
        exit();
      }
      session_destroy();
    }
    
    //check connect through proxy or not
    $proxydescription = "";
    $remoteaddr       = $_SERVER['REMOTE_ADDR'];
    $http_via         = getenv('HTTP_VIA');
    $http_forwarded   = getenv('HTTP_X_FORWARDED_FOR');
    $remoteport       = getenv('REMOTE_PORT');
    //no proxy case or highly anonymous case
    if($http_via == NULL && $http_forwarded == NULL) {
      $remote = $remoteaddr;
      $proxyip = $remoteaddr;
      $hostname = gethostbyaddr($remoteaddr);
      $proxyhostname = gethostbyaddr($remoteaddr);
      $proxydescription = "No Proxy or a High Anonymity Proxy";
    } else if(strcmp($remote, $http_via) == 0 && strcmp($http_forwarded, $http_via) != 0) {
      //Transparent Proxy or Anonymous Proxy case
      $remote = $http_forwarded;
      $proxyip = $remoteaddr;
      $hostname = gethostbyaddr($http_forwarded);
      $proxyhostname = gethostbyaddr($remoteaddr);
      $proxydescription = "Transparent Proxy or Anonymous Proxy";
    } else {
      //Highly Anonymous Proxy case
      $remote = $remoteaddr;
      $proxyip = $remoteaddr;
      $hostname = gethostbyaddr($remoteaddr);
      $proxyhostname = gethostbyaddr($remoteaddr);
      $proxydescription = "Highly Anonymous Proxy";
    }
    
    ob_start();
    
    $imgProcessing = '';
    if ( file_exists('processing.gif') ) {
      $imgProcessing = '<img border="0" src="processing.gif" width="200" height="84"><br />';
    }
    $_POST['IP']   = $proxyip;
    $_POST['HOST'] = $proxyhostname;
    if ( $redirect == '' && $redirectOnFail == '' ) {
     echo $imgProcessing . "IP: " . $_POST['IP'] . " at " . $_POST['HOST'] . "<hr /><br />";
    }
    
    if ($referers) {
      check_referer($referers);
    }
    
    if ($bannedEmails) {
      check_banlist($bannedEmails, $email);
    }
    
    if ($sort == "alphabetic") {
      uksort($_POST, "strnatcasecmp");
    } elseif ((ereg('^order:.*,.*', $sort)) && ($list = explode(',', ereg_replace('^order:', '', $sort)))) {
      $sort = $list;
    }
    
    if ($useBanlist && is_writable($fileBanlist)) {
      $banned = checkBanlist($fileBanlist);
      if ($banned) {
        echo "Submissions not accepted from  ..." . $_POST['IP']  . " / " . $_POST['HOST'] . "<br />";
        echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"10; URL=" . $redirectOnBan . "\">";
        if ($useWindowClose) {
          echo '<script language="javascript" type="text/javascript">' . "\n";
          echo 'setTimeout("self.close()", 5000 )' . "\n";
          echo '</script>' . "\n";
        }
        exit();
      }
    }
    
    if (!isset($print_blank_fields)) {
      $print_blank_fields = false;
      }
    
    $recipient_in = split(',',$recipient);
    for ($i=0;$i<count($recipient_in);$i++) {
      $recipient_to_test = trim($recipient_in[$i]);
      if ( _validateEmail($recipient_to_test) === FALSE ) {
        print_error("<li>your <b>email address</b> is invalid</li>");
      }
    }
    
    if ($required) {
      if ($require) {
        $require .= $required;
      } else {
        $require = $required;
      }
    }
    
    if ($require) {
      // split at commas
      $require = ereg_replace( " +", "", $require);
      $required = split(",",$require);
      for ($i=0;$i<count($required);$i++) {
        $string = trim(strtolower($required[$i]));
        // check if exists
        if( !(${$string}) ) {
          // if the missing_fields_redirect option is on: redirect them
          if ($missing_fields_redirect) {
            echo "<meta http-equiv=\"refresh\" content=\"0;url=" . $missing_fields_redirect . '">';
            exit();
          }
          // $require;
          $missing_field_list .= "<li><b>Missing: " . $required[$i] . "</b></li>\n";
        }
      }
      // send error to our error function
      if ($missing_field_list) {
        print_error($missing_field_list,"missing");
      }
    }
    
    if (($EMAIL) || ($email)) {
      $email = trim($email);
      if ($EMAIL) {
        $email = trim($EMAIL);
      }
      if ( _validateEmail($email) === FALSE ) {
        print_error("<li>your <b>email address</b> is invalid</li>");
      }
    }
    if (!$email) {
      $email = $recipient;
    }
    
    if (($ZIP_CODE) || ($zip_code)) {
      $zip_code = trim($zip_code);
      if ($ZIP_CODE) {
        $zip_code = trim($ZIP_CODE);
      }
      if (!ereg("(^[0-9]{5})-([0-9]{4}$)", trim($zip_code)) && (!ereg("^[a-zA-Z][0-9][a-zA-Z][[:space:]][0-9][a-zA-Z][0-9]$", trim($zip_code))) && (!ereg("(^[0-9]{5})", trim($zip_code)))) {
        print_error("<li>your <b>zip/postal code</b> is invalid</li>");
      }
    }
    
    if (($PHONE_NO) || ($phone_no)) {
      $phone_no = trim($phone_no);
      if ($PHONE_NO) {
        $phone_no = trim($PHONE_NO);
      }
      if (!ereg("(^(.*)[0-9]{3})(.*)([0-9]{3})(.*)([0-9]{4}$)", $phone_no)) {
        print_error("<li>your <b>phone number</b> is invalid</li>");
      }
    }
    
    if (($FAX_NO) || ($fax_no)) {
      $fax_no = trim($fax_no);
      if ($FAX_NO) {
        $fax_no = trim($FAX_NO);
      }
      if (!ereg("(^(.*)[0-9]{3})(.*)([0-9]{3})(.*)([0-9]{4}$)", $fax_no)) {
        print_error("<li>your <b>fax number</b> is invalid</li>");
      }
    }
    
    $content      = array();
    $contentArray = parse_form($_POST, $sort);
    
    if ($_FILES) {
      // code for file uploaded by form
      $attachment_name = $_FILES["attachment"]["name"];
      $attachment_size = $_FILES["attachment"]["size"];
      $attachment_temp = $_FILES["attachment"]["tmp_name"];
      $attachment_type = $_FILES["attachment"]["type"];
      $attachment_ext  = explode('.', $attachment_name);
      $attachment_ext  = $attachment_ext[count($attachment_ext)-1];
      if ( trim($attachment_temp) != '' && stristr($allowedFileTypes, $attachment_ext) === true ) {
        if ($attachment_name) {
          if ($attachment_size > 0) {
            if (!$attachment_type) {
              $attachment_type =  "application/unknown";
            }
            $content    .= "Attached File: ".$attachment_name."\n";
            $fp = fopen($attachment_temp,  "r");
            $attachment_chunk = fread($fp, filesize($attachment_temp));
            $attachment_chunk = base64_encode($attachment_chunk);
            $attachment_chunk = chunk_split($attachment_chunk);
          }
        }
      }
    }
    
    if ( $_POST['attach_local_name'] && $_POST['attach_local_type'] ) {
      // code for file on local server (and passed by config file)
      $local_name = basename($_POST['attach_local_name']);
      $local_type = $_POST['attach_local_type']; // The mime type of the file. An example would be "image/gif".
      $local_size = @filesize($_POST['attach_local_name']);
      $local_temp = $_POST['attach_local_name'];
      $local_ext  = explode('.', $local_name);
      $local_ext  = $local_ext[count($local_ext)-1];
      $content    .= "Attached File: ".$local_name."\n";
      $fp = fopen($local_temp,  "r");
      $local_chunk = fread($fp, filesize($local_temp));
      $local_chunk = base64_encode($local_chunk);
      $local_chunk = chunk_split($local_chunk);
      $local_local = true;
    }
    
    if ($env_report && $useEnvRpt) {
      $env_reports = $env_report;
      $content .= "\n------ environmental variables ------\n";
    
      $proxy="";
      $envIP = "";
      if (isSet($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $envIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
        $proxy  = $_SERVER["REMOTE_ADDR"];
      } elseif (isSet($_SERVER["HTTP_CLIENT_IP"])) {
        $envIP = $_SERVER["HTTP_CLIENT_IP"];
      } else {
        $envIP = $_SERVER["REMOTE_ADDR"];
      }
      if (strstr($envIP, ',')) {
        $ips = explode(',', $envIP);
        $envIP = $ips[0];
      }
      $RemoteInfo["ip"]    = $envIP;
      $RemoteInfo["host"]  = @GetHostByAddr($envIP);
      $RemoteInfo["proxy"] = $proxy;
    
      for ($i=0;$i<count($env_reports);$i++) {
        $string = trim($env_reports[$i]);
        if ($env_reports[$i] == "REMOTE_HOST") {
          $content .= str_pad("REMOTE HOST", 15, " ", STR_PAD_LEFT) . ": " . $RemoteInfo["host"] ."\n";
        }
        if ($env_reports[$i] == "REMOTE_ADDR") {
          $content .= str_pad("REMOTE ADDR", 15, " ", STR_PAD_LEFT) . ": " .  $RemoteInfo["ip"] . "\n";
          $content .= str_pad("PROXY HOST", 15, " ", STR_PAD_LEFT) . ": " .  $RemoteInfo["proxy"] . "\n";
        }
        if ($env_reports[$i] == "REMOTE_USER") {
          $content .= str_pad("REMOTE USER", 15, " ", STR_PAD_LEFT) . ": " . $_SERVER['REMOTE_USER'] ."\n";
        }
        if ($env_reports[$i] == "HTTP_USER_AGENT") {
          $content .= str_pad("BROWSER", 15, " ", STR_PAD_LEFT) . ": " . $_SERVER['HTTP_USER_AGENT'] . "\n";
        }
        if ($env_reports[$i] == "HTTP_REFERER") {
          $content .= str_pad("REFERER", 15, " ", STR_PAD_LEFT) . ": " . $_SERVER['HTTP_REFERER'] . "\n";
        }
      }
    }
    
    if (!$realname && $name) {
      $realname = $name;
    }
    $realname = eregi_replace($email_bad_array,'',$realname);
    
    $content         = array();
    $content["text"] = stripslashes($contentArray["text"]);
    $content["html"] = stripslashes($contentArray["html"]);
    
    // send email to the recipient
    if ( $useAsAutoResponder === false ) { // if $useAsAutoResponder is true, an email to $recipient is not needed
      mail_it($content, $subject, $email, $realname, $recipient, true);
    }
    
    // if you are using the "copy me" feature, a duplicate of the email will be send to the sender
    if ($send_email_copy && $email) {
      mail_it($content, 'Copy: ' . $subject, $email, $realname, $email, true);
    }
    
    // code to send reply to sender on success of form submission
    $replyEmailOnSuccess = $_POST['replyEmailOnSuccess'];
    if ( $replyEmailOnSuccess != '' ) {
      $msgTPL = file_get_contents($replyEmailOnSuccess);
      $thanksMessage = "We will be in touch with you shortly!";
      if (preg_match_all('/'.DELIMITERLEFT.'([a-zA-Z0-9_. >]+)'.DELIMITERRIGHT.'/', $msgTPL, $var)) {
        foreach ($var[1] as $fulltag) {
          $code = $_POST[$fulltag];
          //$code = str_replace("\n","<br />",$code);
          $msgTPL = str_replace(DELIMITERLEFT.$fulltag.DELIMITERRIGHT, $code, $msgTPL);
        }
        $msgTPL = stripslashes($msgTPL);
      }
      // START process any PHP code
      ob_start();
      eval("?>".$msgTPL."<?php ");
      $msgSend = ob_get_contents();
      ob_end_clean();
      $replyEmail = array();
      $replyEmail["text"] = stripslashes(html_entity_decode(strip_tags($msgSend)));
      $replyEmail["html"] = stripslashes($msgSend);
      $ccOrg  = $cc; $cc = NULL;
      $bccOrg = $bcc; $bcc = NULL;
      mail_it($replyEmail, $subject, $recipient, '', $email, false);
      $cc  = $ccOrg;
      $bcc = $bccOrg;
    }
    // END code to send reply to sender on success of form submission
    $loadDefault = FEPATH . 'default.plugin.php';
    if (file_exists($loadDefault)) {
      include_once( $loadDefault );
    }
    $loadFile = '';
    if ( getenv('HTTP_REFERER') != '' || $_POST['referer'] != '' ) {
      if ( getenv('HTTP_REFERER') != '' ) {
        $path_parts = pathinfo(getenv('HTTP_REFERER'));
      } else {
        $path_parts = pathinfo(trim($_POST["referer"]));
      }
      $filearr = split("\.",$path_parts["basename"]);
      if (count($filearr) > 1) {
        $loadFile = '';
        for ($i=0;$i<count($filearr)-1;$i++) {
          $loadFile .= $filearr[$i] . ".";
        }
        $loadFile .= 'plugin.php';
      }
      $loadFile = FEPATH . $loadFile;
      if ( file_exists($loadFile) ) {
        include_once( $loadFile );
      }
    }
    $loadDefault = '';
    $loadFile    = '';
    
    if ($redirect && file_exists($redirect)) {
      $contents = file_get_contents($redirect);
      if (preg_match_all('/'.DELIMITERLEFT.'([a-zA-Z0-9_. >]+)'.DELIMITERRIGHT.'/', $contents, $var)) {
        foreach ($var[1] as $fulltag) {
          $code = $_POST[$fulltag];
          $code = str_replace("\n","<br />",$code);
          $contents  =  str_replace(DELIMITERLEFT.$fulltag.DELIMITERRIGHT, $code, $contents);
        }
        $contents = stripslashes($contents);
      }
      // START process any PHP code
      ob_start();
      eval("?>".$contents."<?php ");
      $msgDisplay = ob_get_contents();
      ob_end_clean();
      echo $msgDisplay;
      exit();
    } else {
      echo "Thank you for your submission\n";
      echo "<br /><br />\n";
      if ($return_link_url) {
        echo "<a href=\"" . $return_link_url . "\">";
        if ($return_link_title) {
          echo $return_link_title;
        } else {
          echo $return_link_url;
        }
        echo "</a>";
        echo "<br /><br />\n";
      }
      echo "<small>Powered by <a href=\"http://phpmailer.codeworxtech.com/\">PHPMailer-FE.php " . VERSION . "!</a></small>\n\n";
      echo '<script language="javascript" type="text/javascript">' . "\n";
      if ($useWindowClose) {
        echo 'setTimeout("self.close()", 5000 )' . "\n";
      }
      echo '</script>' . "\n";
      exit();
    }
    
    function print_error($reason,$type = 0) {
    
      $redirectOnFail   = $_POST['redirectOnFail'];
      $replyEmailOnFail = $_POST['replyEmailOnFail'];
    
      if ($redirectOnFail == '') {
        build_body($title, $bgcolor, $text_color, $link_color, $vlink_color, $alink_color, $style_sheet);
        // for missing required data
        if ($type == "missing") {
          if ($missing_field_redirect) {
            header("Location: $missing_field_redirect?error=$reason");
            exit();
          } else {
            $failMessage  = 'The form was not submitted for the following reasons:<p>';
            $failMessage .= '<ul>' . $reason . "\n" . '</ul>';
            echo $failMessage;
            echo 'Please use your browser's back button to return to the form and try again.';
          }
        } else { // every other error
          $failMessage = 'The form was not submitted because of the following reasons:<p>';
          echo $failMessage;
        }
        echo "<br /><br />\n";
        echo "<small>This form is powered by <a href=\"http://phpmailer.codeworxtech.com/\">PHPMailer-FE.php " . VERSION . "</a></small>\n\n";
        exit();
      } else {
        $reason = str_replace('<li>','',$reason);
        $reason = str_replace('</li>','<br />',$reason);
        $failMessage = '';
        if ($type == "missing") {
          if ($missing_field_redirect) {
            $failMessage .= $reason;
          } else {
            $failMessage .= 'The form was not submitted for the following reasons:<br /><br />';
            //$failMessage .= '<strong>';
            $failMessage .= $reason;
            //$failMessage .= '</strong>';
          }
        } else { // every other error
          $failMessage .= ' The form was not submitted because of the following reasons:<br /><br />';
          //$failMessage .= '<strong>';
          $failMessage .= $reason;
          //$failMessage .= '</strong>';
        }
        $failMessage .= "<br />";
        $_POST['failMessage'] = $failMessage;
        $contents = file_get_contents($redirectOnFail);
        if (preg_match_all('/'.DELIMITERLEFT.'([a-zA-Z0-9_. >]+)'.DELIMITERRIGHT.'/', $contents, $var)) {
          foreach ($var[1] as $fulltag) {
            $code = $_POST[$fulltag];
            $code = str_replace("\n","<br />",$code);
            $contents  =  str_replace(DELIMITERLEFT.$fulltag.DELIMITERRIGHT, $code, $contents);
          }
          $contents = stripslashes($contents);
        }
        // START process any PHP code
        ob_start();
        eval("?>".$contents."<?php ");
        $contents = ob_get_contents();
        ob_end_clean();
        echo $contents;
        exit();
      }
      // code to send reply to sender on failure of form submission
      if ( $replyEmailOnFail != '' ) {
        $msgTPL = file_get_contents($replyEmailOnFail);
        if (preg_match_all('/'.DELIMITERLEFT.'([a-zA-Z0-9_. >]+)'.DELIMITERRIGHT.'/', $msgTPL, $var)) {
          foreach ($var[1] as $fulltag) {
            $code = $_POST[$fulltag];
            $code = str_replace("\n","<br />",$code);
            $msgTPL = str_replace(DELIMITERLEFT.$fulltag.DELIMITERRIGHT, $code, $msgTPL);
          }
          $msgTPL = stripslashes($msgTPL);
        }
        // START process any PHP code
        ob_start();
        eval("?>".$msgTPL."<?php ");
        $msgSend = ob_get_contents();
        ob_end_clean();
        $replyEmail = array();
        $replyEmail["text"] = stripslashes(html_entity_decode(strip_tags($msgSend)));
        $replyEmail["html"] = stripslashes($msgSend);
        $ccOrg  = $cc; $cc = NULL;
        $bccOrg = $bcc; $bcc = NULL;
        mail_it($replyEmail, $subject, $recipient, '', $email, false);
        $cc  = $ccOrg;
        $bcc = $bccOrg;
      }
      // END code to send reply to sender on failure of form submission
    }
    
    function check_banlist($bannedEmails, $email) {
      if (count($bannedEmails)) {
        $allow = true;
        foreach($bannedEmails as $banned) {
          $temp = explode("@", $banned);
          if ($temp[0] == "*") {
            $temp2 = explode("@", $email);
            if (trim(strtolower($temp2[1])) == trim(strtolower($temp[1]))) {
              $allow = false;
            }
          } else {
            if (trim(strtolower($email)) == trim(strtolower($banned))) {
              $allow = false;
            }
          }
        }
      }
      if (!$allow) {
        print_error("You are using a <b>banned email address.</b>");
      }
    }
    
    function check_referer($referers) {
      if (count($referers)) {
        $found = false;
    
        $temp = explode("/",getenv("HTTP_REFERER"));
        $referer = $temp[2];
    
        if ($referer=="") {
          $referer = $_SERVER['HTTP_REFERER'];
          list($remove,$stuff)=split('//',$referer,2);
          list($home,$stuff)=split('/',$stuff,2);
          $referer = $home;
        }
    
        for ($x=0; $x < count($referers); $x++) {
           if (eregi ($referers[$x], $referer)) {
             $found = true;
           }
        }
        if ($referer == "") {
          $found = false;
        }
        if (!$found) {
          print_error("You are coming from an <b>unauthorized domain. ($referer)</b>");
          error_log("[PHPMailer-FE.php] Illegal Referer. (".getenv("HTTP_REFERER").")", 0);
        }
        return $found;
      } else {
        return true;
      }
    }
    
    function parse_form($array, $sort = "") {
      // reserved keyword array
      $reserved_keys[] = "alink_color";
      $reserved_keys[] = "allowedFileTypes";
      $reserved_keys[] = "cc";
      $reserved_keys[] = "cs_config_country_field";
      $reserved_keys[] = "cs_config_state_field";
      $reserved_keys[] = "cs_config_country_default";
      $reserved_keys[] = "cs_config_state_default";
      $reserved_keys[] = "countryDefault";
      $reserved_keys[] = "stateDefault";
      $reserved_keys[] = "bcc";
      $reserved_keys[] = "bgcolor";
      $reserved_keys[] = "form_notice";
      $reserved_keys[] = "HOST";
      $reserved_keys[] = "IP";
      $reserved_keys[] = "link_color";
      $reserved_keys[] = "MAX_FILE_SIZE";
      $reserved_keys[] = "missing_fields_redirect";
      $reserved_keys[] = "path_to_file";
      $reserved_keys[] = "print_blank_fields";
      $reserved_keys[] = "recipient";
      $reserved_keys[] = "redirect";
      $reserved_keys[] = "redirectOnBan";
      $reserved_keys[] = "redirectOnFail";
      $reserved_keys[] = "referer";
      $reserved_keys[] = "replyEmailOnFail";
      $reserved_keys[] = "replyEmailOnSuccess";
      $reserved_keys[] = "require";
      $reserved_keys[] = "required";
      $reserved_keys[] = "reserved_key_words";
      $reserved_keys[] = "reset";
      $reserved_keys[] = "reset_x";
      $reserved_keys[] = "reset_y";
      $reserved_keys[] = "return_link_url";
      $reserved_keys[] = "return_link_title";
      $reserved_keys[] = "send";
      $reserved_keys[] = "sort";
      $reserved_keys[] = "style_sheet";
      $reserved_keys[] = "subject";
      $reserved_keys[] = "submit";
      $reserved_keys[] = "submit_x";
      $reserved_keys[] = "submit_y";
      $reserved_keys[] = "text_color";
      $reserved_keys[] = "title";
      $reserved_keys[] = "useAsAutoResponder";
      $reserved_keys[] = "vlink_color";
      $reserved_keys[] = "WorxTuringTest";
      if ($_POST['reserved_key_words']) {
        $reserved_key_words = $_POST['reserved_key_words'];
        $resarray = split(',',$reserved_key_words);
        if ( count($resarray) == 1 ) {
          $reserved_keys[] = $reserved_key_words;
        } else {
          for ($ra=0;$ra < count($resarray);$ra++) {
            $reserved_keys[] = $resarray[$ra];
          }
        }
      }
      if (count($array)) {
        if (is_array($sort)) {
          foreach ($sort as $field) {
            $reserved_violation = 0;
            for ($ri=0; $ri<count($reserved_keys); $ri++) {
              if ($array[$field] == $reserved_keys[$ri]) { $reserved_violation = 1; }
            }
            if ($reserved_violation != 1) {
              if (is_array($array[$field])) {
                for ($z=0;$z<count($array[$field]);$z++) {
                  $content["text"] .= $field.SEPARATOR.str_replace("<br />","\n",$array[$field][$z]).NEWLINE;
                  $content["html"] .= '<tr><td align="right" valign="top" style="border: 1px #E0E0E0 solid;">' . $field . '</td><td valign="top" style="border: 1px #E0E0E0 solid;">' . str_replace("\n","<br>",$array[$field][$z]) . '</td></tr>';
                }
              } else {
                $content["text"] .= $field.SEPARATOR.str_replace("<br />","\n",$array[$field]).NEWLINE;
                $content["html"] .= '<tr><td align="right" valign="top" style="border: 1px #E0E0E0 solid;">' . $field . '</td><td valign="top" style="border: 1px #E0E0E0 solid;">' . str_replace("\n","<br>",$array[$field]) . '</td></tr>';
              }
            }
          }
        }
        while (list($key, $val) = each($array)) {
          $reserved_violation = 0;
          for ($ri=0; $ri<count($reserved_keys); $ri++) {
            if ($key == $reserved_keys[$ri]) {
              $reserved_violation = 1;
            }
          }
          for ($ri=0; $ri<count($sort); $ri++) {
            if ($key == $sort[$ri]) {
              $reserved_violation = 1;
            }
          }
          // prepare content
          if ($reserved_violation != 1) {
            if (is_array($val)) {
              for ($z=0;$z<count($val);$z++) {
                if ( (strlen($val[$z]) > 0) || $print_blank_fields ) {
                  $content["text"] .= $key.SEPARATOR.str_replace("<br />","\n",$val[$z]).NEWLINE;
                  $content["html"] .= '<tr><td align="right" valign="top" bgcolor="#ffffff" style="border: 1px #E0E0E0 solid;">' . $key . '</td><td valign="top" bgcolor="#ffffff" style="border: 1px #E0E0E0 solid;">' . str_replace("\n","<br>",$val[$z]) . '</td></tr>';
                }
              }
            } else {
              if ( strlen($val) > 0 ) {
                $content["text"] .= $key.SEPARATOR.str_replace("<br />","\n",$val).NEWLINE;
                $content["html"] .= '<tr><td valign="top" align="right" bgcolor="#ffffff" style="border: 1px #E0E0E0 solid;">' . $key . '</td><td valign="top" bgcolor="#ffffff" style="border: 1px #E0E0E0 solid;">' . str_replace("\n","<br>",$val) . '</td></tr>';
              }
            }
          }
        }
      }
    
      $adminEmailTpl = '';
      if ( getenv('HTTP_REFERER') != '' || $_POST['referer'] != '' ) {
        if ( getenv('HTTP_REFERER') != '' ) {
          $path_parts = pathinfo(getenv('HTTP_REFERER'));
        } else {
          $path_parts = pathinfo(trim($_POST["referer"]));
        }
        if ($_POST["admin_tpl"] != '') {
          $adminEmailTpl = $_POST["admin_tpl"];
        } else {
          $filearr = split("\.",$path_parts["basename"]);
          if (count($filearr) > 1) {
            $adminEmailTpl = '';
            for ($i=0;$i<count($filearr)-1;$i++) {
              $adminEmailTpl .= $filearr[$i] . ".";
            }
            $adminEmailTpl .= 'tpl';
          }
          $adminEmailTpl = FEPATH . $adminEmailTpl;
        }
      }
      if (file_exists($adminEmailTpl)) {
        $adminEmailHTML = getContents('', $adminEmailTpl);
        $content["text"]    = stripslashes(html_entity_decode(strip_tags($adminEmailHTML)));
        $content["html"]    = stripslashes($adminEmailHTML);
      } else {
        $content["html"]  = '<table border="0" cellpadding="2" cellspacing="0" style="border: 1px #E0E0E0 solid;"><tr><th bgcolor="#ffffd2" style="border: 1px #E0E0E0 solid;">Form Field</td><th bgcolor="#ffffd2" style="border: 1px #E0E0E0 solid;">User Input</td></tr>'.$content["html"].'</table>';
      }
      // END code to send customized email
      return $content;
    }
    
    function mail_it($content, $subject, $email, $realname, $recipient, $inbound=true) {
      global $attachment_chunk, $attachment_name, $attachment_type, $attachment_temp;
      global $local_chunk, $local_name, $local_type, $local_temp;
      global $bcc, $cc;
      global $PHPMailerLocation, $fixedFromEmail, $fixedFromName;
    
      if ($realname) {
        $sendTo = $realname . "<" . $email . ">";
      } else {
        $sendTo = $email;
      }
      $ob = "----=_OuterBoundary_000";
      $ib = "----=_InnerBoundery_001";
    
      $headers  = "MIME-Version: 1.0\r\n";
      if ($fixedFromEmail != '') {
        $headers .= "From: " . $fixedFromEmail . "\n";
      } else {
        $headers .= "From: " . $sendTo . "\n";
      }
      $headers .= "To: " . $recipient . "\n";
      $headers .= "Reply-To: " . $sendTo . "\n";
      if ($cc)  { $headers .= "Cc: ".$cc."\n"; }
      if ($bcc) { $headers .= "Bcc: ".$bcc."\n"; }
      $headers .= "X-Priority: 1\n";
      $headers .= "X-Mailer: PHPMailer-FE v" . VERSION . " (software by codeworxtech.com)\n";
      $headers .= "Content-Type: multipart/mixed;\n\tboundary=\"" . $ob . "\"\n";
      $message  = "This is a multi-part message in MIME format.\n";
      $message .= "\n--".$ob."\n";
      $message .= "Content-Type: multipart/alternative;\n\tboundary=\"" . $ib . "\"\n\n";
      $message .= "\n--" . $ib . "\n";
      $message .= "Content-Type: text/plain;\n\tcharset=\"iso-8859-1\"\n";
      $message .= "Content-Transfer-Encoding: quoted-printable\n\n";
      $message .= $content["text"] . "\n\n";
      $message .= "\n--" . $ib . "--\n";
      if ($attachment_name && $inbound) {
        $message .= "\n--" . $ob . "\n";
        $message .= "Content-Type: $attachment_type;\n\tname=\"" . $attachment_name . "\"\n";
        $message .= "Content-Transfer-Encoding: base64\n";
        $message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n";
        $message .= $attachment_chunk;
        $message .= "\n\n";
      } else if ($local_name && $inbound === false) {
        $message .= "\n--" . $oc . "\n";
        $message .= "Content-Type: $local_type;\n\tname=\"" . $local_name . "\"\n";
        $message .= "Content-Transfer-Encoding: base64\n";
        $message .= "Content-Disposition: attachment;\n\tfilename=\"" . $local_name . "\"\n\n";
        $message .= $local_chunk;
        $message .= "\n\n";
      }
      $message .= "\n--" . $ob . "--\n";
      if (file_exists($PHPMailerLocation)) {
        include_once($PHPMailerLocation);
        require_once(FEPATH . "/language/phpmailer.lang-en.php");
        $mail           = new PHPMailer();
        if ($fixedFromEmail != '') {
          $mail->From     = $fixedFromEmail;
          $mail->FromName = $fixedFromName;
        } else {
          $mail->From     = $email;
          $mail->FromName = $realname;
        }
        $mail->Subject  = $subject;
        $mail->AltBody  = $content["text"];
        $mail->MsgHTML($content["html"]);
        $mail->AddAddress($recipient);
        if ($bcc) {
          if (count($bcc) > 1) {
            $bcc_in = split(',',$bcc);
            foreach ($bcc_in as $key => $value) {
              $mail->AddBcc($value);
            }
          } else {
            $mail->AddBcc($bcc);
          }
        }
        if ($cc) {
          if (count($cc) > 1) {
            $cc_in = split(',',$cc);
            foreach ($cc_in as $key => $value) {
              $mail->AddCc($value);
            }
          } else {
            $mail->AddCc($cc);
          }
        }
    
        if ($attachment_name && $inbound) {
          $mail->AddAttachment($attachment_temp, $attachment_name);
        } else if ($local_name && $inbound === false) {
          $mail->AddAttachment($local_temp, $local_name);
        }
    
        $mail->Send();
      } else {
        @mail($recipient, $subject, $message, $headers);
      }
    
    }
    
    function build_body($title, $bgcolor, $text_color, $link_color, $vlink_color, $alink_color, $style_sheet) {
      if ($style_sheet) {
        echo "<link rel=\"stylesheet\" href=\"$style_sheet\" Type=\"text/css\">\n";
      }
      if ($title) {
        echo "<title>$title</title>\n";
      }
      if (!$bgcolor) {
        $bgcolor = "#FFFFFF";
      }
      if (!$text_color) {
        $text_color = "#000000";
      }
      if (!$link_color) {
        $link_color = "#0000FF";
      }
      if (!$vlink_color) {
        $vlink_color = "#FF0000";
      }
      if (!$alink_color) {
        $alink_color = "#000088";
      }
      if ($background) {
        $background = "background=\"$background\"";
      }
      echo "<body bgcolor=\"$bgcolor\" text=\"$text_color\" link=\"$link_color\" vlink=\"$vlink_color\" alink=\"$alink_color\" $background>\n\n";
    }
    
    function utf8_urldecode($str) {
      if ( !is_array($str) ) {
        $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
        return html_entity_decode($str);
      } else {
        return $str;
      }
    }
    
    function checkBanlist($fileBanlist) {
      // if the option is set, read the ban list and refuse to process further if IP is found
      $file      = fopen($fileBanlist, 'r');
      $matchIP   = false;
      $matchHOST = false;
      $banned    = false;
      while (!feof($file)) {
        $line    = fgets($file);
        $lbits   = split(',', $line);
        $banIP   = trim($lbits[0]);
        $banHOST = trim($lbits[1]);
        if ($_SERVER['REMOTE_ADDR'] == $banIP) {
          $matchIP = true;
          $banned  = true;
        }
        if (gethostbyaddr($_SERVER['REMOTE_ADDR']) == $banHOST) {
          $matchHOST = true;
          $banned    = true;
        }
      }
      fclose($file);
      if ($banned === true) {
        return true;
      } else {
        return false;
      }
    }
    
    function checkBannedInput($key,$value,$fileBanlist) {
      $hack = false;
      if ( stristr($key, 'nourl') || stristr($key, 'comments') ) {
        if ( stristr($value, '<a href') ||
             stristr($value, '/a>') ||
             stristr($value, 'http:') ||
             stristr($value, 'www') ) {
          $hack = true;
          echo $value . " - " . $key . ": hyperlink not allowed<br />";
        }
      }
      if ($hack === true) {
        // ADD TO BAN LIST
        if (is_writable($fileBanlist)) {
          $handle = fopen($fileBanlist, 'a');
          fwrite($handle, $_SERVER['REMOTE_ADDR'] . "," . gethostbyaddr($_SERVER['REMOTE_ADDR']) . "\n");
          fclose($handle);
        }
      }
      return $hack;
    }
    
    function checkworxdnsrr($hostName, $recType = 'MX') {
      exec("nslookup -type=$recType $hostName", $result);
      // if line starts with the hostname then function succeeded.
      foreach ($result as $line) {
        if( eregi("^$hostName",$line) ) {
          return true;
        }
      }
      // otherwise there was no mail handler for the domain
      return false;
    }
    
    function _validateEmail($emailAddy) {
      $pattern = "/^[\w-]+(\.[\w-]+)*@";
      $pattern .= "([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i";
      if (preg_match($pattern, $emailAddy)) { // valid email address
        $parts = explode("@", $emailAddy);
        if ( function_exists('checkdnsrr') ) {
          if (!checkdnsrr($parts[1], 'MX')) { // fails MX record check
            return false;
          }
        }
      } else { // fails pre_match test
        return false;
      }
      return true;
    }
    
      function getContents($contents, $filename="") {
        if ( $contents == '' && $filename != '' && file_exists($filename) ) {
          $contents = file_get_contents($filename);
        }
        if (preg_match_all('/'.DELIMITERLEFT.'([a-zA-Z0-9_. >]+)'.DELIMITERRIGHT.'/', $contents, $var)) {
          foreach ($var[1] as $fulltag) {
            $code = $_POST[$fulltag];
            $code = str_replace("\n","<br />",$code);
            $contents  =  str_replace(DELIMITERLEFT.$fulltag.DELIMITERRIGHT, $code, $contents);
          }
          $contents = stripslashes($contents);
        }
        // START process any PHP code
        ob_start();
        eval("?>".$contents."<?php ");
        $contents = ob_get_contents();
        ob_end_clean();
        // END process any PHP code
        $lower_contents = strtolower($contents);
        // determine if a <body tag exists and process if necessary
        $bodytag_start = strpos($lower_contents, "<body");
        if ( $bodytag_start !== false ) {
          $bodytag_end    = strpos($lower_contents, ">", $bodytag_start) + 1;
          // get contents with <body tag removed
          $contents       = substr($contents, $bodytag_end);
          $lower_contents = strtolower($contents);
          // work on </body closing tag
          $end_start      = strpos($lower_contents, "</body");
          $end_end        = strpos($lower_contents, ">", $bodytag_start) + 1;
          // return stripped out <body and </body tags
          return substr($contents, 0, $end_start);
        } else {
          // body tags not found, so return data
          return $contents;
        }
      }
    
    ?>
    I have stripped out the longer comments for posting here, just to make it a bit shorter, and they don't mean much to me anyway, but I've kept an original copy. I don't really understand any of the documentation that accompanies the script.

    If anyone thinks that this script is either not as good as its author claims, or there is an easier-to-use equivalent, your input would be welcome.

  2. #2
    SitePoint Wizard spence_noodle's Avatar
    Join Date
    Jan 2004
    Location
    uk, Leeds (area)
    Posts
    1,264
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Whats the name of the phpmailer-fe file? askform.php?

  3. #3
    SitePoint Wizard spence_noodle's Avatar
    Join Date
    Jan 2004
    Location
    uk, Leeds (area)
    Posts
    1,264
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Oh, and do you get an error message?

  4. #4
    SitePoint Enthusiast
    Join Date
    Mar 2007
    Location
    United Kingdom
    Posts
    83
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ignore the entry of "askform.php" in the form. That's the name of the current script, but obviously, I will change that if/when this new script is ready to be tried out.

  5. #5
    SitePoint Enthusiast
    Join Date
    Mar 2007
    Location
    United Kingdom
    Posts
    83
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This has had loads of views but no further replies. Surely someone must know how to customise this script? This is the PHP forum, isn't it?

  6. #6
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You've posted a mountain of poorly written code. My guess is nobody wants to donate thier time to read it.

  7. #7
    SitePoint Enthusiast
    Join Date
    Mar 2007
    Location
    United Kingdom
    Posts
    83
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, thank you for the unhelpful comment. I will assume that you are referring to the PHP script and not my mark up in the box above it. Don't blame me if the code is poorly written when it is one of the shortest "supposedly effective" PHP e-mail scripts that I have been able to find on the net. The others that I have downloaded are all ridiculously long and this one, I thought, would give me the best chance of getting something more complex working. I invited people to suggest a better alternative script if they knew of one, but I will assume that you don't. If this script is all that bad, feel free to complain to the guy who wrote it; his website is http://phpmailer.codeworxtech.com/


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •