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

追加した

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 に答える
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 に答える