【问题标题】:how to solve "Warning: file_get_contents() error" message - contact form?如何解决“警告:file_get_contents() 错误”消息 - 联系表?
【发布时间】:2021-08-30 06:37:00
【问题描述】:

当我点击 unfilled 联系表单上的“发送”按钮时,我的 javascript 验证消息出现,然后我收到错误消息:

完整的错误信息:

Warning: file_get_contents(): Filename cannot be empty in mail.php on line 19
mail send ... OK

之后会发生什么:

我收到一封带有附件“Part 2.bin”的空电子邮件

我想要发生的事情

如果我尝试“发送”未归档的联系表单,我希望显示我的 javascript 验证并阻止提交联系表单,直到填写所有必填字段。

我尝试过这样做:

<form  name="contactForm"  action="php/mail.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm()">

onsubmit="validateForm(); return false;" 而不是onsubmit="return validateForm()"

会发生什么 显示联系表单验证消息,但出现另一个问题

另一个问题:当我尝试提交完整的联系表格时,它没有提交......(没有错误消息......)

我对 PHP 和 Javascript 还很陌生,我在这个问题上卡住了 3 天...有人请救救我

// Defining a function to display error message
function printError(elemId, hintMsg) {
    document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form 
function validateForm() {
    // Retrieving the values of form elements 
    let name = document.contactForm.name.value;
    let email = document.contactForm.email.value;
    let country = document.contactForm.country.value;
    let subject = document.contactForm.subject.value;

    
    // Defining error variables with a default value
    let nameValidation = emailValidation = countryValidation = subjectValidation;
    
    // Validate name
    if(name == "") {
        printError("nameValidation", "Please enter your name");
    } else {
        let regex = /^[a-zA-Z\s]+$/;                
        if(regex.test(name) === false) {
            printError("nameValidation", "Please enter a valid name");
        } else {
            printError("nameValidation", "");
            nameValidation = false;
        }
    }
    
    // Validate email address
    if(email == "") {
        printError("emailValidation", "Please enter your email address");
    } else {
        // Regular expression for basic email validation
        let regex = /^\S+@\S+\.\S+$/;
        if(regex.test(email) === false) {
            printError("emailValidation", "Please enter a valid email address");
        } else{
            printError("emailValidation", "");
            emailValidation = false;
        }
    }
    
  
    // Validate country
    if(country == "Select") {
        printError("countryValidation", "Please select your country");
    } else {
        printError("countryValidation", "");
        countryValidation = false;
    }
  
   // Validate subject
    if(subject == "Select") {
        printError("subjectValidation", "Please select the subject");
    } else {
        printError("subjectValidation", "");
        subjectValidation = false;
    }
    
 
    
    // Prevent the form from being submitted if there are any errors
    if((nameValidation || emailValidation || countryValidation || subjectValidation) == true) {
       return false;
    } else {
        // Creating a string from input data for preview
        let dataPreview = "You've entered the following details: \n" +
                          "Full Name: " + name + "\n" +
                          "Email Address: " + email + "\n" +                          
                          "Country: " + country + "\n" +
                          "Subject: " + subject + "\n"; 
        // if(hobbies.length) {
        //     dataPreview += "Hobbies: " + hobbies.join(", ");
        // }
        // Display input data in a dialog box before submitting the form
        // alert(dataPreview);
    }
};
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
    <link rel="stylesheet" href="css/style.css"/>
    <script src="/js/contact-form-validation.js" ></script>
    
    <style>
    body {  width: 100%;  height: 100vh;  display: flex;  justify-content: center;  align-items: center;  background-color: aquamarine; }section {  width: 300px; }form {  display: flex;  flex-direction: column;  background-color: #f2f2f2;  padding: 3rem 1rem; }input, select {  margin-bottom: 1rem; }label {  font-weight: bold; }  .validation-message {    color: red;    font-size: 90%;}
    </style>
</head>
<body>

<section>
     
    <form  name="contactForm" onsubmit="return validateForm()" action="confirmation.php" method="post">
        <!-- name -->
        <label for="name">Full name</label>
        <input type="text" id="name" name="name" placeholder="Your full name.."  />
        <div class="validation-message" id="nameValidation"></div>
        <!-- email -->
        <label for="email">Email</label>
        <input type="email" id="email" name="email" placeholder="Your e-mail.."  />
        <div class="validation-message" id="emailValidation"></div>
        <!-- country -->
        <label for="country">Country</label>
        <select id="country" name="country" >
            <option>Select</option>
            <option value="Afghanistan">Afghanistan</option>
            <option value="Åland Islands">Åland Islands</option>
            <option value="Zambia">Zambia</option>
            <option value="Zimbabwe">Zimbabwe</option>
        </select>
        <div class="validation-message" id="countryValidation"></div>
        <!-- subject -->
        <label for="subject">Subject</label>
        <select id="subject" name="subject" >
            <option>Select</option>
            <option value="Media Enquiries">Media Enquiries</option>
            <option value="Donation Enquiries">Donation Enquiries</option>
            <option value="Volunteering Enquiries">Volunteering Enquiries</option>
            <option value="Collaboration Enquiries">Collaboration Enquiries</option>
            <option value="Reporting Scams">Reporting Scams</option>
            <option value="Other">Other.. (Specify in the message field )</option>
        </select>
        <div class="validation-message" id="subjectValidation"></div>
        <!-- attach file -->
        <label style="font-weight: normal; font-size: 12px;" for="message">docx and pdf formats</label>
        <input type="file" id="attachment-file" name="file">
        
        <!-- message text area -->
        <label for="message">Message</label>
        <textarea id="message" name="message" placeholder="Write your message here.."
            style="height:100px"></textarea>
        <!--  send button-->
           <input type="submit" id="send-button" name="submit" value="Send" />
    </form>
</section>

</body>
</html>

ma​​il.php

<?php
    $userAttachment =  $_FILES['file']['name'];
    $userAttachmentName = $_FILES['file']['tmp_name']; 
    $userName = $_POST['name'];
    $userEmail = $_POST['email'];
    $userCountry = $_POST['country'];
    $userSubject = $_POST['subject'];
    $userMessage = $_POST['message'];     
    $message ="\r\n  Name: ". $userName . "\r\n  Email: " . $userEmail . "\r\n  Country: " . $userCountry . "\r\n  Subject: " . $userSubject . "\r\n\r\n  Message: \r\n\r\n  " . $userMessage; 
    $subject = "[ ".$userSubject." ]"." from ". "[ ".$userCountry." ]";
    $fromname = "Contact Form";
    $fromemail = 'autoreply@email.com';  //if u dont have an email create one on your cpanel
    $mailto = 'example@example.com';  //the email which u want to recv this email
 **(THIS IS LINE 19) -->**   $content = file_get_contents($userAttachmentName);  
    $content = chunk_split(base64_encode($content));
    // a random hash will be necessary to send mixed content
    $separator = md5(time());
    // carriage return type (RFC)
    $eol = "\r\n";
    // main header (multipart mandatory)
    $headers = "From: ".$fromname." <".$fromemail.">" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;
    // message
    $body = "--" . $separator . $eol;
    $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $body .= "Content-Transfer-Encoding: 8bit" . $eol;
    $body .= $message . $eol;
    // attachment
    $body .= "--" . $separator . $eol;
    $body .= "Content-Type: application/octet-stream; name=\"" . $userAttachment . "\"" . $eol;
    $body .= "Content-Transfer-Encoding: base64" . $eol;
    $body .= "Content-Disposition: attachment" . $eol;
    $body .= $content . $eol;
    $body .= "--" . $separator . "--";
    //SEND Mail
    if (mail($mailto, $subject, $body, $headers)) {
        echo "mail send ... OK"; // do what you want after sending the email
        
        
    } else {
        echo "mail send ... ERROR!";
        print_r( error_get_last() );
    }

【问题讨论】:

    标签: javascript php contact-form


    【解决方案1】:

    return false 将停止提交。

    你需要多部分来获取文件

    试试这个

    <form  name="contactForm"  action="php/mail.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm()">
    

    您需要使用默认值定义验证 - 现在您只需使用 null 定义它们

    let nameValidation = emailValidation = countryValidation = subjectValidation = true;
    

    然后你需要在你调用错误的地方将它们设置为 false,而不是在 else 中

     printError("nameValidation", "Please enter your name");
     nameValidation = false;
    

    并将 validateForm 函数更改为在不正常时返回 false,在正常时返回 true:

    return emailValidation && countryValidation && subjectValidation;
    

    在函数的最后

    代码:

    // Defining a function to display error message
    function printError(elemId, hintMsg) {
      document.getElementById(elemId).innerHTML = hintMsg;
    }
    
    // Defining a function to validate form 
    document.getElementById("contactForm").addEventListener("submit",function(e) {
      // Retrieving the values of form elements 
      let fullname = this.fullname.value;
      let email = this.email.value;
      let country = this.country.value;
      let subject = this.subject.value;
    
    
      // Defining error variables with a default value
      let nameValidation = emailValidation = countryValidation = subjectValidation = true;
    
    
      // Validate name
      printError("nameValidation", "");
      if (fullname == "") {
        printError("nameValidation", "Please enter your name");
        nameValidation = false;
      } else {
        let regex = /^[a-zA-Z\s]+$/;
        if (regex.test(fullname) === false) {
          printError("nameValidation", "Please enter a valid name");
          nameValidation = false;
        }
      }
    
      // Validate email address
      printError("emailValidation", "");
      if (email == "") {
        printError("emailValidation", "Please enter your email address");
        emailValidation = false;
      } else {
        // Regular expression for basic email validation
        let regex = /^\S+@\S+\.\S+$/;
        if (regex.test(email) === false) {
          printError("emailValidation", "Please enter a valid email address");
          emailValidation = false;
        }
      }
    
      // Validate country
      printError("countryValidation", "");
      if (country == "Select") {
        printError("countryValidation", "Please select your country");
        countryValidation = false;
      }
    
    
    
      // Validate subject
      printError("subjectValidation", "");
      if (subject == "Select") {
        printError("subjectValidation", "Please select the subject");
        subjectValidation = false;
      }
    
    
    
      // Prevent the form from being submitted if there are any errors
      if (!nameValidation || !emailValidation || !countryValidation || !subjectValidation) {
        e.preventDefault(); // stop submission
        return false;
      }
      // Creating a string from input data for preview
      let dataPreview = "You've entered the following details: \n" +
        "Full Name: " + fullname + "\n" +
        "Email Address: " + email + "\n" +
        "Country: " + country + "\n" +
        "Subject: " + subject + "\nSubmit?";
      if (!confirm(dataPreview)) {
        e.preventDefault(); // stop submission
      }
    });
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Contact Form</title>
      <link rel="stylesheet" href="css/style.css" />
      <script src="/js/contact-form-validation.js"></script>
    
      <style>
        body {
          width: 100%;
          height: 100vh;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: aquamarine;
        }
        
        section {
          width: 300px;
        }
        
        form {
          display: flex;
          flex-direction: column;
          background-color: #f2f2f2;
          padding: 3rem 1rem;
        }
        
        input,
        select {
          margin-bottom: 1rem;
        }
        
        label {
          font-weight: bold;
        }
        
        .validation-message {
          color: red;
          font-size: 90%;
        }
      </style>
    </head>
    
    <body>
    
      <section>
    
        <form id="contactForm" action="confirmation.php" method="post">
          <!-- name -->
          <label for="name">Full name</label>
          <input type="text" id="fullname" name="fullname" placeholder="Your full name.." />
          <div class="validation-message" id="nameValidation"></div>
          <!-- email -->
          <label for="email">Email</label>
          <input type="email" id="email" name="email" placeholder="Your e-mail.." />
          <div class="validation-message" id="emailValidation"></div>
          <!-- country -->
          <label for="country">Country</label>
          <select id="country" name="country">
            <option>Select</option>
            <option value="Afghanistan">Afghanistan</option>
            <option value="Åland Islands">Åland Islands</option>
            <option value="Zambia">Zambia</option>
            <option value="Zimbabwe">Zimbabwe</option>
          </select>
          <div class="validation-message" id="countryValidation"></div>
          <!-- subject -->
          <label for="subject">Subject</label>
          <select id="subject" name="subject">
            <option>Select</option>
            <option value="Media Enquiries">Media Enquiries</option>
            <option value="Donation Enquiries">Donation Enquiries</option>
            <option value="Volunteering Enquiries">Volunteering Enquiries</option>
            <option value="Collaboration Enquiries">Collaboration Enquiries</option>
            <option value="Reporting Scams">Reporting Scams</option>
            <option value="Other">Other.. (Specify in the message field )</option>
          </select>
          <div class="validation-message" id="subjectValidation"></div>
          <!-- attach file -->
          <label style="font-weight: normal; font-size: 12px;" for="message">docx and pdf formats</label>
          <input type="file" id="attachment-file" name="file">
    
          <!-- message text area -->
          <label for="message">Message</label>
          <textarea id="message" name="message" placeholder="Write your message here.." style="height:100px"></textarea>
          <!--  send button-->
          <input type="submit" id="send-button" value="Send" />
        </form>
      </section>
    
    </body>
    
    </html>

    【讨论】:

    • 啊,您还需要将验证移到打印后
    • @PaulC 查看完整和简化的代码。我也从名字改为全名,所以 $userName = $_POST['fullname']; 。并从提交按钮中删除了 name="submit"。
    • 我看到你颠倒了逻辑,emailValidation=false 表示没问题。这对我来说很难,所以我实际上扭转了测试。请看我如何使用 addEventListener 和 e.preventDefault 来停止提交
    • 我也在正则表达式中用全名更新了代码
    • 这不是 JS 问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    相关资源
    最近更新 更多