making formmail.php work (get rid of unauthorized domain error.)

Mendel

Mr. Upgrade
Veteran
Okay, I'm doing this form thingie for a website. I get this error message:

You are coming from an <b>unauthorized domain.</b>

The problem is, the form seems to work for some people, but not for others. So I was thinking... if I just removed some if part of that php, would it just send the form no matter what or would it just remove the error message? I've never done any php coding. I just linked the form to this formmail.php that they seemed to use in their previous website.

So what changes would I need to do to make the thing work no matter what the referer etc? Maybe a firewall configuration problem? (I don't have access to the server, I just desperately try to make the website)

If there is a way to certainly fix it by doing some changes, please list the working code in your reply...

Oh by the way, is it ok to list the domain just as nicedomain.com if the form is at nicedomain.com/english/feedback.htm for example?

Thanks for any help in advance. here's the source, I've just altered all the domain info so to not reveal my client. (I hope)

Code:
<?
/*
##############################################################################
# PLEASE DO NOT REMOVE THIS HEADER!!!
#
# COPYRIGHT NOTICE
#
# FormMail.php v5.0
# Copyright 2000-2004 Ai Graphics and Joe Lumbroso (c) All rights reserved.
# Created 07/06/2000   Last Modified 10/28/2003
# Joseph Lumbroso, http://www.aigraphics.com, http://www.dtheatre.com
#                  http://www.dtheatre.com/scripts/
##############################################################################
#
# This cannot and will not be inforced but I would appreciate a link back
# to any of these sites:
# http://www.dtheatre.com
# http://www.aigraphics.com
# http://www.dtheatre.com/scripts/
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
##############################################################################
*/

// for ultimate security, use this instead of using the form
$recipient = "recipient@nicedomain.com"; // youremail@domain.com
//$recipient = "recipient2@nicedomain.com"; // youremail@domain.com

// bcc emails (separate multiples with commas (,))
$bcc = "";

// referers.. domains/ips that you will allow forms to
// reside on.
$referers = array ('´nicedomain.com');  //is this ok?

// or do I need to make it http://www.nicedomain.com? or some such

// banned emails, these will be email addresses of people
// who are blocked from using the script (requested)
$banlist = array ('*@someotherdomain.com', 'user@domain.com', 'etc@domains.com');

// field / value seperator
define("SEPARATOR", ($separator)?$separator:": ");

// content newline
define("NEWLINE", ($newline)?$newline:"\n");

// formmail version (for debugging mostly)
define("VERSION", "5.0");


// our mighty error function..
function print_error($reason,$type = 0) {
   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 {
      ?>
      The form was not submitted for the following reasons:<p>
      <ul><?
      echo $reason."\n";
      ?></ul>
      Please use your browser's back button to return to the form and try again.<?
      }
   } else { // every other error
      ?>
      The form was not submitted because of the following reasons:<p>
      <?
   }
   echo "<br><br>\n";
   echo "<small>This form is powered by <a href=\"http://www.dtheatre.com/scripts/\">Jack's Formmail.php ".VERSION."</a></small>\n\n";
   exit;
}

// function to check the banlist
// suggested by a whole lot of people.. Thanks
function check_banlist($banlist, $email) {
   if (count($banlist)) {
      $allow = true;
      foreach($banlist 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 from a <b>banned email address.</b>");
   }
}

// function to check the referer for security reasons.
// contributed by some one who's name got lost.. Thanks
// goes out to him any way.
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.</b>");
         error_log("[FormMail.php] Illegal Referer. (".getenv("HTTP_REFERER").")", 0);
      }
         return $found;
      } else {
         return true; // not a good idea, if empty, it will allow it.
   }
}
if ($referers)
   check_referer($referers);

if ($banlist)
   check_banlist($banlist, $email);

// This function takes the sorts, excludes certain keys and 
// makes a pretty content string.
function parse_form($array, $sort = "") {
   // build reserved keyword array
   $reserved_keys[] = "MAX_FILE_SIZE";
   $reserved_keys[] = "required";
   $reserved_keys[] = "redirect";
   $reserved_keys[] = "require";
   $reserved_keys[] = "path_to_file";
   $reserved_keys[] = "recipient";
   $reserved_keys[] = "subject";
   $reserved_keys[] = "sort";
   $reserved_keys[] = "style_sheet";
   $reserved_keys[] = "bgcolor";
   $reserved_keys[] = "text_color";
   $reserved_keys[] = "link_color";
   $reserved_keys[] = "vlink_color";
   $reserved_keys[] = "alink_color";
   $reserved_keys[] = "title";
   $reserved_keys[] = "missing_fields_redirect";
   $reserved_keys[] = "env_report";
   $reserved_keys[] = "submit";
   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 .= $field.SEPARATOR.$array[$field][$z].NEWLINE;
               } else
                  $content .= $field.SEPARATOR.$array[$field].NEWLINE;
            }
         }
      }
      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++)
                  $content .= $key.SEPARATOR.$val[$z].NEWLINE;
            } else
               $content .= $key.SEPARATOR.$val.NEWLINE;
         }
      }
   }
   return $content;
}

// mail the content we figure out in the following steps
function mail_it($content, $subject, $email, $recipient) {
   global $attachment_chunk, $attachment_name, $attachment_type, $attachment_sent, $bcc;

   $ob = "----=_OuterBoundary_000";
   $ib = "----=_InnerBoundery_001";
   
   $headers  = "MIME-Version: 1.0\r\n"; 
   $headers .= "From: ".$email."\n"; 
   $headers .= "To: ".$recipient."\n"; 
   $headers .= "Reply-To: ".$email."\n";
   if ($bcc) $headers .= "Bcc: ".$bcc."\n"; 
   $headers .= "X-Priority: 1\n"; 
   $headers .= "X-Mailer: DT Formmail".VERSION."\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."\n\n";
   $message .= "\n--".$ib."--\n";
   if ($attachment_name && !$attachment_sent) {
      $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";
      $attachment_sent = 1;
   }
   $message .= "\n--".$ob."--\n";
   
   mail($recipient, $subject, $message, $headers);
}

// take in the body building arguments and build the body tag for page display
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";
}

// check for a recipient email address and check the validity of it
// Thanks to Bradley miller (bradmiller@accesszone.com) for pointing
// out the need for multiple recipient checking and providing the code.
$recipient_in = split(',',$recipient);
for ($i=0;$i<count($recipient_in);$i++) {
   $recipient_to_test = trim($recipient_in[$i]);
   if (!eregi("^[_\\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\\.)+[a-z]{2,6}$", $recipient_to_test)) {
      print_error("<b>I NEED VALID RECIPIENT EMAIL ADDRESS ($recipient_to_test) TO CONTINUE</b>");
   }
}

// This is because I originally had it require but too many people
// were used to Matt's Formmail.pl which used required instead.
if ($required)
   $require = $required;
// handle the required fields
if ($require) {
   // seperate at the commas
   $require = ereg_replace( " +", "", $require);
   $required = split(",",$require);
   for ($i=0;$i<count($required);$i++) {
      $string = trim($required[$i]);
      // check if they exsist
      if((!(${$string})) || (!(${$string}))) {
         // if the missing_fields_redirect option is on: redirect them
         if ($missing_fields_redirect) {
            header ("Location: $missing_fields_redirect");
            exit;
         }
         $require;
         $missing_field_list .= "<b>Missing: $required[$i]</b><br>\n";
      }
   }
   // send error to our mighty error function
   if ($missing_field_list)
      print_error($missing_field_list,"missing");
}

// check the email fields for validity
if (($email) || ($EMAIL)) {
   $email = trim($email);
   if ($EMAIL) $email = trim($EMAIL);
   if (!eregi("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,6}$", $email))
      print_error("your <b>email address</b> is invalid");
   $EMAIL = $email;
}

// check zipcodes for validity
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("your <b>zip/postal code</b> is invalid");
}

// check phone for validity
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("your <b>phone number</b> is invalid");
}

// check phone for validity
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("your <b>fax number</b> is invalid");
}

// sort alphabetic or prepare an order
if ($sort == "alphabetic") {
   uksort($HTTP_POST_VARS, "strnatcasecmp");
} elseif ((ereg('^order:.*,.*', $sort)) && ($list = explode(',', ereg_replace('^order:', '', $sort)))) {
   $sort = $list;
}
   
// prepare the content
$content = parse_form($HTTP_POST_VARS, $sort);

// check for an attachment if there is a file upload it
if ($attachment_name) {
   if ($attachment_size > 0) {
      if (!$attachment_type) $attachment_type =  "application/unknown";
      $content .= "Attached File: ".$attachment_name."\n";
      $fp = fopen($attachment,  "r");
      $attachment_chunk = fread($fp, filesize($attachment));
      $attachment_chunk = base64_encode($attachment_chunk);
      $attachment_chunk = chunk_split($attachment_chunk);
   }
}

// check for a file if there is a file upload it
if ($file_name) {
   if ($file_size > 0) {
      if (!ereg("/$", $path_to_file))
         $path_to_file = $path_to_file."/";
      $location = $path_to_file.$file_name;
      if (file_exists($path_to_file.$file_name))
         $location = $path_to_file.rand(1000,3000).".".$file_name;
      copy($file,$location);
      unlink($file);
      $content .= "Uploaded File: ".$location."\n";
   }
}

// second file (see manual for instructions on how to add more.)
if ($file2_name) {
   if ($file_size > 0) {
      if (!ereg("/$", $path_to_file))
         $path_to_file = $path_to_file."/";
      $location = $path_to_file.$file2_name;
      if (file_exists($path_to_file.$file2_name))
         $location = $path_to_file.rand(1000,3000).".".$file2_name;
      copy($file2,$location);
      unlink($file2);
      $content .= "Uploaded File: ".$location."\n";
   }
}

// if the env_report option is on: get eviromental variables
if ($env_report) {
   $env_report = ereg_replace( " +", "", $env_report);
   $env_reports = split(",",$env_report);
   $content .= "\n------ eviromental variables ------\n";
   for ($i=0;$i<count($env_reports);$i++) {
      $string = trim($env_reports[$i]);
      if ($env_reports[$i] == "REMOTE_HOST")
         $content .= "REMOTE HOST: ".$REMOTE_HOST."\n";
      if ($env_reports[$i] == "REMOTE_USER")
         $content .= "REMOTE USER: ". $REMOTE_USER."\n";
      if ($env_reports[$i] == "REMOTE_ADDR")
         $content .= "REMOTE ADDR: ". $REMOTE_ADDR."\n";
      if ($env_reports[$i] == "HTTP_USER_AGENT")
         $content .= "BROWSER: ". $HTTP_USER_AGENT."\n";
   }
}

// send it off
mail_it(stripslashes($content), ($subject)?stripslashes($subject):"Form Submission", $email, $recipient);
if (file_exists($ar_file)) {
   $fd = fopen($ar_file, "rb");
   $ar_message = fread($fd, filesize($ar_file));
   fclose($fd);
   mail_it($ar_message, ($ar_subject)?stripslashes($ar_subject):"RE: Form Submission", ($ar_from)?$ar_from:$recipient, $email);
}

// if the redirect option is set: redirect them
if ($redirect) {
   header("Location: $redirect");
   exit;
} else {
   echo "Thank you for your submission\n";
   echo "<br><br>\n";
   echo "<small>This form is powered by <a href=\"http://www.dtheatre.com/scripts/\">Jack's Formmail.php ".VERSION."!</a></small>\n\n";
   exit;
}

// <----------    THE END    ----------> //
 
Last edited by a moderator:
depends on what kind of spam filters some people have.... so its more likely that problem is in headers that are sent. i didnt go thru all the code, but my thats my guess....

(and i just woke up, so i need my cofee fix first)
 
silence said:
depends on what kind of spam filters some people have.... so its more likely that problem is in headers that are sent. i didnt go thru all the code, but my thats my guess....

(and i just woke up, so i need my cofee fix first)

That would seem to be the problem. Tell the people who are having trouble to disable their firewall and try it.
 
silence said:
depends on what kind of spam filters some people have.... so its more likely that problem is in headers that are sent. i didnt go thru all the code, but my thats my guess....

(and i just woke up, so i need my cofee fix first)

Uh, what do spam filters have to do with this? AFAIK, spam filters are only part of problem once some kind of email is actually sent. The problem here is, once the error message is given, we don't get that far. No email is sent. So nothing will get as far as to the spam filters.

What do you mean by that headers thing? Who sends them and when?
 
madmartyau said:
That would seem to be the problem. Tell the people who are having trouble to disable their firewall and try it.

Oh and asking customers to disable their firewalls will probably not be greeted with much kind words nowadays. On the other hand... If there is any specific setting change in the firewall, that might be more likely changed.
 
Well the problem is presumably in the checkreferers function. So I would try putting that in a script on it's own so that you can do some debugging.
Make it output the variables at various stages and get the people to try it and see where things diverge.

I have just started playing with php myself. I have used it to do a solar positon placemark for google earth :)
 
What is happening is that it's checking the domains in the $referers array against the HTTP_REFERER server environment variable (this is the address of the refering page). If the domain(s) in the $referers array do not match the refering page then you get the error you are seeing. Try checking the error log it appears to write out (line 132) for more info. Note you will need to make sure your browser is set to send the HTTP_REFERER string, as you can block this in FireFox and Opera (not a good idea).

What you need to change, I think, is the following line to include the correct refering domain:
Code:
$referers = array ('nicedomain.com');
Change "nicedomain.com" to the actual refering domain that you will allow mail to be sent from. This would be the name of the domain the script is running on and/or ones that post data to the script.

If you don't want it to be blocked by ANY referer then remove the call to the fuction check_referer() on line 139-140:
Code:
if ($referers)
   check_referer($referers);
Delete or comment out the above two lines to do this.
 
Last edited by a moderator:
Does the referrer info matter to you? If not just delete that section of code. Some firewall software i.e Norton blocks referrer info.
 
Mendel said:
Uh, what do spam filters have to do with this? AFAIK, spam filters are only part of problem once some kind of email is actually sent. The problem here is, once the error message is given, we don't get that far. No email is sent. So nothing will get as far as to the spam filters.

What do you mean by that headers thing? Who sends them and when?

Diplo looked into the code and gave you much better answer, but some spam filters work by reading headers and not allowing "unknown" senders to go thru..... hope that helps.
Sorry if i wasnt much help.... without coffee my brain is like Doom3 on Pentium II and RivaTNT ;)


EDIT ::

here, i checked formmail's page....

@referers = ('scriptarchive.com','YOUR_IP'); This array allows you to define the domains on which you allow forms to reside and use this installation of FormMail. If a user tries to put a form on another server, that is not scriptarchive.com, they will receive an error message when someone tries to fill out their form. By placing scriptarchive.com in the @referers array, this also allows www.scriptarchive.com, ftp.scriptarchive.com, any other http address with scriptarchive.com in it and scriptarchive.com's IP address to access this script as well, so no users will be turned away. NOTE: This is not a security check. Referer headers can EASILY be faked. Rather, it prevents someone on xyznotyou.com from using the FormMail on your server to process forms on their server on a regular basis. It remains in the script as a remnant of earlier versions when it was used for security, but the @recipients variable is now used to specify exactly who can receive e-mail from this installation.

As of version 1.7, the domains listed here are also used as the defaults when checking valid recipient e-mail addresses. You should either include all domain names that you wish to have FormMail send e-mails to in your @referers array or tailor the @recipients array by hand.
 
Last edited by a moderator:
Thanks Diplo. I will try removing those two lines when I get back to office next week.

There's lots of other lines mentioning the referer thing though, should I leave them untouched?

edit: Oh I see, I think those other lines won't be executed if those two lines are removed, yeah..
 
Last edited by a moderator:
Mendel said:
edit: Oh I see, I think those other lines won't be executed if those two lines are removed, yeah..
Correct :) Removing the call to the function stops all lines of code in the function being executed.
 
Looking at the code i dont think its good idea to remove it....

Code:
$referers = array ('nicedomain.com');

i think this sets up which domain are authorised to send mail via your server and if you turn that down you might open your server to anyone, including spammers to abuse it for sending mail.... i dont know what kind of site or system you are making, but IMO, all you need is to put either 'localhost' (if you are testing on local server) or your acctual domain (if you are testing on live server) there to make it work....

for beyond3d it would be....

Code:
$referers = array ('beyond3d.com');

or

$referers = array ('http://www.beyond3d.com');

read my post where i pasted from Formmail's FAQ....
 
Yes of course I had the correct referer in the code originally. I just replaced it so not to reveal my client :)

The problem was, it was reported that the form then worked for some people but didn't for others.

Now I will have to negotiate with the client on if they want those two lines removed or if they think its too much of a security problem.
 
heh.... yeah, let client decide or try making something less complicated.
i use pretty standard forms without too much checking, i just use sessions so noone can spam with reloading page, other then that its totally basic stuff (and it works ;) )
 
Back
Top