1

我已经整理了一个包含多个文本字段和 3 个文件上传的联系表。代码如下:

<?php

$websitename=""; 
$allowtypes=array("jpg", "tif", "pdf" );
$myemail="...";
$priority="3"; 
$allowattach="3"; 
$max_file_size="1024";
$max_file_total="3072";
$submitvalue=" Submit "; 
$resetvalue=" Reset ";
$defaultsubject="Registration"; 
$use_subject_drop=false;
$subjects=array("Department 1", "Department 2", "Department 3");
$emails=array("dept_1@domain.com", "dept_2@domain.com", "dept_3@domain.com");
$thanksmessage="Thank you for submitting your registration!"; 

function get_ext($key) { 
    $key=strtolower(substr(strrchr($key, "."), 1));
    $key=str_replace("jpeg", "jpg", $key);
    return $key;
}

function phattach($file, $name, $boundary) {

    $fp=fopen($file, "r");
    $str=fread($fp, filesize($file));
    $str=chunk_split(base64_encode($str));
    $message="--".$boundary."\n";
    $message.="Content-Type: application/octet-stream; name=\"".$name."\"\n";
    $message.="Content-disposition: attachment; filename=\"".$name."\"\n"; 
    $message.="Content-Transfer-Encoding: base64\n";
    $message.="\n";
    $message.="$str\n";
    $message.="\n";

    return $message;
}

function clean_msg($key) {
    $key=str_replace("\r", "", $key);
    $key=str_replace("\n", "", $key);
    $find=array(
        "/bcc\:/i",
        "/Content\-Type\:/i",
        "/Mime\-Type\:/i",
        "/cc\:/i",
        "/to\:/i"
    );
  $key=preg_replace($find, "", $key);
  return $key;
}

$error="";
$sent_mail=false;

If($_POST['submit']==true) {
    extract($_POST, EXTR_SKIP);

        If(trim($firstname)=="") { 
            $error.="You did not enter your first name!<br />";
        }
        If(trim($lastname)=="") { 
            $error.="You did not enter your last name!<br />";
        }
        If(trim($dateofbirth)=="") { 
            $error.="You did not enter your date of birth!<br />";
        }
        If(trim($streetaddress)=="") { 
            $error.="You did not enter your address!<br />";
        }
        If(trim($postalcode)=="") { 
            $error.="You did not enter your postal code!<br />";
        }
        If(trim($city)=="") { 
            $error.="You did not enter your city!<br />";
        }
        If(trim($country)=="") { 
            $error.="You did not enter your country!<br />";
        }
        If(trim($videolink)=="") { 
            $error.="You did not enter a video link!<br />";
        }
        If(trim($email)=="") { 
            $error.="You did not enter your email!<br />";
        } 
            Elseif(!preg_match("/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/", $email)) {
            $error.="Invalid email address.<br />";
        }

        If(trim($emailsubject)=="") {
            $emailsubject=$defaultsubject;
        }

        If($allowattach > 0) {

            If((array_sum($_FILES['attachment']['size'])) > ($max_file_total*1024)) {

                $error.="The max size allowed for all your files is ".$max_file_total."kb<br />";

            } Else {

                For($i=0; $i <= $allowattach-1; $i++) {

                    If($_FILES['attachment']['name'][$i]) {

                        If(!in_array(get_ext($_FILES['attachment']['name'][$i]), $allowtypes)) {

                            $error.= "Invalid file type for your file: ".$_FILES['attachment']['name'][$i]."<br />";

                        } Elseif(($_FILES['attachment']['size'][$i]) > ($max_file_size*1024)) {

                            $error.= "Your file: ".$_FILES['attachment']['name'][$i]." is too big.<br />";

                        }   
                    } 
                }
            }
        }

    If($error) {

        $display_message=$error;

    } Else {

        If($use_subject_drop AND is_array($subjects) AND is_array($emails)) {
            $subject_count=count($subjects);
            $email_count=count($emails);

            If($subject_count==$email_count) {

                $myemail=$emails[$emailsubject];
                $emailsubject=$subjects[$emailsubject];
            }
        }

        $boundary=md5(uniqid(time()));

        $headers="Return-Path: <".clean_msg($email).">\n";
        $headers.="From: ".clean_msg($yourname)." <".clean_msg($email).">\n";
        $headers.="X-Mailer: PHP/".phpversion()."\n";
        $headers.="X-Sender: ".$_SERVER['REMOTE_ADDR']."\n";
        $headers.="X-Priority: ".$priority."\n"; 
        $headers.="MIME-Version: 1.0\n";
        $headers.="Content-Type: multipart/mixed; boundary=\"".$boundary."\"\n";
        $headers.="This is a multi-part message in MIME format.\n";

        $message = "--".$boundary."\n";
        $message.="Content-Type: text/html; charset=\"iso-8859-1\"\n";
        $message.="Content-Transfer-Encoding: quoted-printable\n";
        $message.="\n";
        $message.="<br /><br />First Name:<br />";
        $message.=clean_msg(nl2br(strip_tags($firstname)));
        $message.="<br /><br />Last Name:<br />";
        $message.=clean_msg(nl2br(strip_tags($lastname)));
        $message.="<br /><br />Date of Birth:<br />";
        $message.=clean_msg(nl2br(strip_tags($dateofbirth)));
        $message.="<br /><br />Street Address:<br />";
        $message.=clean_msg(nl2br(strip_tags($streetaddress)));
        $message.="<br /><br />Postal Code:<br />";
        $message.=clean_msg(nl2br(strip_tags($postalcode)));
        $message.="<br /><br />City:<br />";
        $message.=clean_msg(nl2br(strip_tags($city)));
        $message.="<br /><br />Country:<br />";
        $message.=clean_msg(nl2br(strip_tags($country)));
        $message.="<br /><br />Email:<br />";
        $message.=clean_msg(nl2br(strip_tags($email)));
        $message.="<br /><br />Website:<br />";
        $message.=clean_msg(nl2br(strip_tags($website)));
        $message.="<br /><br />Videolink:<br />";
        $message.=clean_msg(nl2br(strip_tags($videolink)));
        $message.="<br /><br />Video Password:<br />";
        $message.=clean_msg(nl2br(strip_tags($password)));
        $message.="<br /><br />Links:<br />";
        $message.=clean_msg(nl2br(strip_tags($link1)));
        $message.="<br />";
        $message.=clean_msg(nl2br(strip_tags($link2)));
        $message.="<br />";
        $message.=clean_msg(nl2br(strip_tags($link3)));
        $message.="<br /><br /><br />";
        $message.="\n";

        If($allowattach > 0) {

            For($i=0; $i <= $allowattach-1; $i++) {

                If($_FILES['attachment']['tmp_name'][$i]) {

                    $message.=phattach($_FILES['attachment']['tmp_name'][$i], $_FILES['attachment']['name'][$i], $boundary);

                }   
            }
        }

        $message.="--".$boundary."--\n";

        If(!mail($myemail, clean_msg($emailsubject), $message, $headers)) {

            Exit("An error has occured, please report this to the website administrator.\n");

        } Else {

            $sent_mail=true;            
        }
    }
}

这可能不是很漂亮,但似乎可以解决问题。但我不知道的是,当没有或没有足够的文件选择上传时如何给出错误消息。我以不同的方式尝试了以下命令,有时它根本不做任何事情,有时它显示错误消息,即使选择了文件。

1.

if((!empty($_FILES["attachment"])) && ($_FILES['attachment']['error'] == 0)) { 
        $error.="You did not submit all the required files!<br />";
    }

2.

} if (isset ($_FILES['attachment']['name']) && !empty ($_FILES['attachment']['name'])) {

                            $error.= "Please attach all the required files!<br />";

3.

if ($_FILES["attachment"]["error"] ==4) {
            $error.="You need to attach the required files.<br />";
        }

4.

    foreach($_FILES as $file) {
        if($file['error'] == 0 && $file['size'] ==0) {
        $error.="You did not submit all the required files!<br />";
    }
}

如何实现仅在选择上传的文件少于 3 个时才显示的错误警告?

所以,我包括了这个:

<script type="text/javascript">
  function check_form(){
var all_ok=1;
      var errors="";
if(document.getElementById('firstname').value == ''){}
           all_ok=0;
           errors+="You did not enter your first name!<br />";
        }
if(document.getElementById('lastname').value == ''){}
           all_ok=0;
           errors+="You did not enter your last name!<br />";
        }
if(document.getElementById('dateofbirth').value == ''){}
           all_ok=0;
           errors+="You did not enter your date of birth!<br />";
        }
if(document.getElementById('streetaddress').value == ''){}
           all_ok=0;
           errors+="You did not enter your address!<br />";
        }
if(document.getElementById('postalcode').value == ''){}
           all_ok=0;
           errors+="You did not enter your postal code!<br />";
        }
if(document.getElementById('city').value == ''){}
           all_ok=0;
           errors+="You did not enter your city!<br />";
        }
if(document.getElementById('country').value == ''){}
           all_ok=0;
           errors+="You did not enter your country!<br />";
        }
if(document.getElementById('videolink').value == ''){}
           all_ok=0;
           errors+="You did not enter your video link!<br />";
        }
if(document.getElementById('email').value == ''){}
           all_ok=0;
           errors+="You did not enter your email!<br />";
        }
if(document.getElementById('attachment').value == ''){}
           all_ok=0;
           errors+="You did not attach all the required files!<br />";
        }

    if(all_ok){
           document.getElementById('theform').submit();
      }else{
           alert(errors);
      }
  }
  </script>

并将提交更改为:

<input type="submit" onclick='check_form()' value="<?=$submitvalue;?>" /> &nbsp;
            <input type="reset" value="<?=$resetvalue;?>" />

它什么都不做?我也尝试添加

If(trim($_FILES["attachment"])=="") { 
            $error.="You did not attach all the required files!<br />";
        }

在 php 中,但即使选择了文件,这也会给我一条错误消息。

4

2 回答 2

0

为什么不使用 javascript 在提交之前检查表单?就像是:

  <button onclick='check_form()'>SEND FORM</button>

然后在head标签中类似:

  <script>
  function check_form(){
      var all_ok=1;
      var errors="";
      if(document.getElementById('firstname').value == ''){}
           all_ok=0;
           errors+="Please fill the first name of the form<br/>";
      }
      // more ifs to check the other inputs
      if(all_ok){
           document.getElementById('form_id').submit();
      }else{
           alert(errors);
           //if you want to make it more pretty than an alert you can use a 
           //empty div and put the errors inside of it.
           //document.getElementById('errors_div').innerHTML='<p>'+errors+'</p>'; 
      }

  }
  </script>
于 2013-01-08T15:45:23.187 回答
0

我添加了

If(($_FILES['attachment']['size'][$i]) == (0)) {
$error.= "A required attachment is missing!<br />";
}

For($i=0; $i <= $allowattach-1; $i++)

这会为每个丢失的文件生成一条错误消息。

感谢 Naryl 的贡献。

于 2013-01-09T18:08:33.400 回答