dongxie45083 2012-10-23 09:48
浏览 32
已采纳

文件上传和发送到电子邮件帐户

On my website I have the following HTML5 form:

<form action="briefform.php" method="post" enctype="multipart/form-data" name="servicesform" id="servicesform" autocomplete="on"> 
    <fieldset>
        <ul>
            <li><label>Name*</label>
                <input name="name" type="text" class="name">
            </li>
            <li><label>Email*</label>
                <input name="email" type="email" class="email">
            </li>
            <li><label>Business Name</label>
                <input name="busname" type="text" id="busname">
            </li>
            <li><label>Business Description</label>
                <textarea name="busdisc" id="busdisc"></textarea>
            </li>
            <li><label>Budget (AUD)</label>
                <input name="budget" type="number" id="budget" placeholder="$">
            </li>
            <li><label>Time Frame</label>
                <input name="timeframe" type="text" id="timeframe">
            </li>
            <li><label>Project Title</label>
                <input name="protitle" type="text" id="protitle" >
            </li>
            <li><label>Project Description*</label>
                <textarea name="prodisc" id="prodisc" spellcheck="true"></textarea>
            </li>
            <li><label>Upload</label>
                <input name="uploads[]" type="file" id="uploads" multiple>
            </li>
            <li><label>Target Audience</label>
                <textarea name="target" id="target"></textarea>
            </li>
            <li><label>Further Details</label>
                <textarea name="requirements" id="requirements" spellcheck="true"></textarea>
            </li>
            <li><input type="reset" name="reset" class="reset" value="Reset"/>
                <input type="submit" name="submit" class="submit" value="Send"/>
            </li>
        </ul>
    </fieldset>
</form>

Which is being processed by this PHP script:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Name</title>
<meta http-equiv="refresh" content="15;URL=http://mysiteaddress.com/">
</head>

<style>
    body {
        background: #202024;
        font: .75em Arial, Helvetica, sans-serif;
        color: #FFF;
        text-align: center;
        margin-top: 25%;
    }
</style>
<body>

<?php
    if(isset($_POST['email'])) {

        // TO AND FROM
        $email_to = "myemail@address.com";
        $email_subject = "Message from MYSITE.COM";

        function died($error) {
            // ERROR MESSAGES TO THE USER
            echo "We are very sorry, but there were error(s) found with the form you submitted. ";
            echo "These errors appear below.<br /><br />";
            echo $error."<br /><br />";
            echo "Please go back and fix these errors.<br /><br />";
            die();
        }

        // VALIDATION ON EXPECTED DATA
        if(!isset($_POST['name']) ||
            !isset($_POST['email']) ||
            !isset($_POST['busname']) ||
            !isset($_POST['busdisc']) ||
            !isset($_POST['budget']) ||
            !isset($_POST['timeframe']) ||
            !isset($_POST['protitle']) ||
            !isset($_POST['prodisc']) ||
            !isset($_POST['target']) ||
            !isset($_POST['requirements'])) {
            died('We are sorry, but there appears to be a problem with the form you submitted.');      
        }

        $name_from = $_POST['name']; // required
        $email_from = $_POST['email']; // required
        $busname = $_POST['busname']; // not required
        $busdisc = $_POST['busdisc']; // not required
        $budget = $_POST['budget']; // not required
        $timeframe = $_POST['timeframe']; // not required
        $protitle = $_POST['protitle']; // not required
        $prodisc = $_POST['prodisc']; // required
        $uploads = $_POST['uploads']; // not required
        $target = $_POST['target']; // not required
        $requirements = $_POST['requirements']; // not required         

        // MANDATORY FIELDS 
        $error_message = "";
        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
          if(!preg_match($email_exp,$email_from)) {
            $error_message .= 'The email address you entered does not appear to be valid.<br />';
          }
            $string_exp = "/^[A-Za-z .'-]+$/";
          if(!preg_match($string_exp,$name_from)) {
            $error_message .= 'The name you entered does not appear to be valid.<br />';
          }
          if(!preg_match($string_exp,$prodisc)) {
            $error_message .= 'The project description you entered does not appear to be valid.<br />';
          }

          if(strlen($error_message) > 0) {
            died($error_message);
          }
        $email_message = "Services Form.

";

        function clean_string($string) {
          $bad = array("content-type","bcc:","to:","cc:","href");
          return str_replace($bad,"",$string);
        }

        $email_message .= "Name: ".clean_string($name_from)."
";
        $email_message .= "Email: ".clean_string($email_from)."
";
        $email_message .= "Business Name: ".clean_string($busname)."
";
        $email_message .= "Business Description: ".clean_string($busdisc)."
";
        $email_message .= "Budget: ".clean_string($budget)."
";
        $email_message .= "Timeframe: ".clean_string($timeframe)."
";
        $email_message .= "Project Title: ".clean_string($protitle)."
";
        $email_message .= "Project Description: ".clean_string($prodisc)."
";
        $email_message .= "Uploads: ".clean_string($uploads)."
";
        $email_message .= "Target Audience: ".clean_string($target)."
";
        $email_message .= "Further Requirements: ".clean_string($requirements)."
";

        // FILE UPLOADS
        $allowedExts = array("ai", "doc", "docx", "gif", "jpeg", "jpg", "pdf", "png", "psd");
        $extension = end(explode(".", $_FILES["uploads"]["name"]));

        if ((($_FILES["file"]["type"] == "image/gif")
        || ($_FILES["file"]["type"] == "image/jpeg")
        || ($_FILES["file"]["type"] == "image/png")
        || ($_FILES["file"]["type"] == "image/pjpeg"))
        && ($_FILES["file"]["size"] < 20000)
        && in_array($extension, $allowedExts)) {
           if ($_FILES["file"]["error"] > 0) {
             echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
             }
           else {
              echo "Upload: " . $_FILES["file"]["name"] . "<br />";
              echo "Type: " . $_FILES["file"]["type"] . "<br />";
              echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
              echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
                 if (file_exists("upload/" . $_FILES["file"]["name"])) {
                    echo $_FILES["file"]["name"] . " already exists. ";
           }
              else {
                move_uploaded_file($_FILES["file"]["tmp_name"],
                 "upload/" . $_FILES["file"]["name"]);
                 echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
              }
           }
        }
        else {
           echo "Invalid file";
        }

    // EMAIL HEADERS
    $headers = 'From: '.$email_from."
".
    'Reply-To: '.$email_from."
" .
    'X-Mailer: PHP/' . phpversion();
    @mail($email_to, $email_subject, $email_message, $headers); 
?>

<!-- SUCCESS MESSAGE -->
Your message has been sent.  Thank you for contacting me, I'll get back to you as soon as possible.

<?php
}
?>
</body>
</html>

I've created a folder on my directory called upload, which I believe is where the script uploads the files to.

When the user submits the form with the required fields, the information gets sent to my email account.

However, if the user would like to send a file/files as well, the script isn't processing this and the user receives an "Invalid file" echo above the "Your message has been sent. ... " feedback.

If I then head over to my email account, I can see the information was sent successfully (even with the "Invalid file" error), but the files uploaded by the user are missing and not located in my uploads folder.

Using the script above, how would I achieve the file upload part?

Thank you.

  • 写回答

1条回答 默认 最新

  • dounuo9921 2012-10-23 10:09
    关注

    OK.. Completely new answer. There's a few issues with the code. I have it running on my server.

    I'm not going to get into multi-file uploads right now.

    <form action="briefform.php" method="post" enctype="multipart/form-data" name="servicesform" id="servicesform" autocomplete="on"> 
        <fieldset>
            <ul>
                <li><label>Name*</label>
                    <input name="name" type="text" class="name">
                </li>
                <li><label>Email*</label>
                    <input name="email" type="email" class="email">
                </li>
                <li><label>Business Name</label>
                    <input name="busname" type="text" id="busname">
                </li>
                <li><label>Business Description</label>
                    <textarea name="busdisc" id="busdisc"></textarea>
                </li>
                <li><label>Budget (AUD)</label>
                    <input name="budget" type="number" id="budget" placeholder="$">
                </li>
                <li><label>Time Frame</label>
                    <input name="timeframe" type="text" id="timeframe">
                </li>
                <li><label>Project Title</label>
                    <input name="protitle" type="text" id="protitle" >
                </li>
                <li><label>Project Description*</label>
                    <textarea name="prodisc" id="prodisc" spellcheck="true"></textarea>
                </li>
                <li><label>Upload</label>
                    <input name="uploads" type="file" id="uploads" multiple>
                </li>
                <li><label>Target Audience</label>
                    <textarea name="target" id="target"></textarea>
                </li>
                <li><label>Further Details</label>
                    <textarea name="requirements" id="requirements" spellcheck="true"></textarea>
                </li>
                <li><input type="reset" name="reset" class="reset" value="Reset"/>
                    <input type="submit" name="submit" class="submit" value="Send"/>
                </li>
            </ul>
        </fieldset>
    </form>
    

    So, first thing, change the form to

    <input name="uploads" type="file" id="uploads" multiple>
    

    Now for the script..

    <!doctype html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Site Name</title>
    <meta http-equiv="refresh" content="15;URL=http://mysiteaddress.com/">
    </head>
    
    <style>
        body {
            background: #202024;
            font: .75em Arial, Helvetica, sans-serif;
            color: #FFF;
            text-align: center;
            margin-top: 25%;
        }
    </style>
    <body>
    
    <?php
        if(isset($_POST['email'])) {
    
            // TO AND FROM
            $email_to = "myemail@address.com";
            $email_subject = "Message from MYSITE.COM";
    
            function died($error) {
                // ERROR MESSAGES TO THE USER
                echo "We are very sorry, but there were error(s) found with the form you submitted. ";
                echo "These errors appear below.<br /><br />";
                echo $error."<br /><br />";
                echo "Please go back and fix these errors.<br /><br />";
                die();
            }
    
            // VALIDATION ON EXPECTED DATA
            if(!isset($_POST['name']) ||
                !isset($_POST['email']) ||
                !isset($_POST['busname']) ||
                !isset($_POST['busdisc']) ||
                !isset($_POST['budget']) ||
                !isset($_POST['timeframe']) ||
                !isset($_POST['protitle']) ||
                !isset($_POST['prodisc']) ||
                !isset($_POST['target']) ||
                !isset($_POST['requirements'])) {
                died('We are sorry, but there appears to be a problem with the form you submitted.');      
            }
    
            $name_from = $_POST['name']; // required
            $email_from = $_POST['email']; // required
            $busname = $_POST['busname']; // not required
            $busdisc = $_POST['busdisc']; // not required
            $budget = $_POST['budget']; // not required
            $timeframe = $_POST['timeframe']; // not required
            $protitle = $_POST['protitle']; // not required
            $prodisc = $_POST['prodisc']; // required
            $uploads = $_FILES['uploads']; // not required
    

    It's not $_POST['uploads']. It's $_FILES. You should use the $uploads value from now on in the script.

            $target = $_POST['target']; // not required
            $requirements = $_POST['requirements']; // not required         
    
            // MANDATORY FIELDS 
            $error_message = "";
            $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
              if(!preg_match($email_exp,$email_from)) {
                $error_message .= 'The email address you entered does not appear to be valid.<br />';
              }
                $string_exp = "/^[A-Za-z .'-]+$/";
              if(!preg_match($string_exp,$name_from)) {
                $error_message .= 'The name you entered does not appear to be valid.<br />';
              }
              if(!preg_match($string_exp,$prodisc)) {
                $error_message .= 'The project description you entered does not appear to be valid.<br />';
              }
    
              if(strlen($error_message) > 0) {
                died($error_message);
              }
            $email_message = "Services Form.
    
    ";
    
            function clean_string($string) {
              $bad = array("content-type","bcc:","to:","cc:","href");
              return str_replace($bad,"",$string);
            }
    
            $email_message .= "Name: ".clean_string($name_from)."
    ";
            $email_message .= "Email: ".clean_string($email_from)."
    ";
            $email_message .= "Business Name: ".clean_string($busname)."
    ";
            $email_message .= "Business Description: ".clean_string($busdisc)."
    ";
            $email_message .= "Budget: ".clean_string($budget)."
    ";
            $email_message .= "Timeframe: ".clean_string($timeframe)."
    ";
            $email_message .= "Project Title: ".clean_string($protitle)."
    ";
            $email_message .= "Project Description: ".clean_string($prodisc)."
    ";
            $email_message .= "Uploads: ".clean_string($uploads)."
    ";
            $email_message .= "Target Audience: ".clean_string($target)."
    ";
            $email_message .= "Further Requirements: ".clean_string($requirements)."
    ";
    
            // FILE UPLOADS
            $allowedExts = array("ai", "doc", "docx", "gif", "jpeg", "jpg", "pdf", "png", "psd");
            $extension = end(explode(".", $_FILES["uploads"]["name"]));
    

    It's all good until here. Out of nowhere you started using $_FILES["file"], I assume from piecing together tutorials. Either $_FILES["uploads"], or $uploads is valid at this point

            if ((($_FILES["uploads"]["type"] == "image/gif")
            || ($_FILES["uploads"]["type"] == "image/jpeg")
            || ($_FILES["uploads"]["type"] == "image/png")
            || ($_FILES["uploads"]["type"] == "image/pjpeg"))
            && ($_FILES["uploads"]["size"] < 20000)
    

    This is a really small image. 20000 bytes is only 20kB. I'm guessing you pulled this part from here http://www.w3schools.com/php/php_file_upload.asp. You may want to use

           ($_FILES["uploads"]["size"] < 200000)   
    

    for a 200kB image, or

           ($_FILES["uploads"]["size"] < 200000)   
    

    for a 2MB image

            && in_array($extension, $allowedExts)) {
    

    Here's another issue. I'll expand the if statement so it's more easily read.

    if(
    
        (
                ($_FILES["file"]["type"] == "image/gif"  ) ||   
                ($_FILES["file"]["type"] == "image/jpeg" ) || 
                ($_FILES["file"]["type"] == "image/png"  ) ||
                ($_FILES["file"]["type"] == "image/pjpeg")      
    
        )
    
        && 
    
                ($_FILES["file"]["size"] < 20000)
    
        && 
    
                in_array($extension, $allowedExts)
    
    ) 
    

    You've basically said, if the metadata is for a gif, png, or jpg, AND it is less than 20kb AND it is either a Adobe Illustrator, Word Document, image, PDF, or photoshop file

    That will be true if it's an image. An AI, PDF, or DOC will never pass the uploads type check.

               if ($_FILES["uploads"]["error"] > 0) {
                 echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
                 }
               else {
                  echo "Upload: " . $_FILES["uploads"]["name"] . "<br />";
                  echo "Type: " . $_FILES["uploads"]["type"] . "<br />";
                  echo "Size: " . ($_FILES["uploads"]["size"] / 1024) . " Kb<br />";
                  echo "Temp file: " . $_FILES["uploads"]["tmp_name"] . "<br />";
                     if (file_exists("upload/" . $_FILES["uploads"]["name"])) {
                        echo $_FILES["uploads"]["name"] . " already exists. ";
               }
                  else {
                    move_uploaded_file($_FILES["uploads"]["tmp_name"],
                     "upload/" . $_FILES["uploads"]["name"]);
                     echo "Stored in: " . "upload/" . $_FILES["uploads"]["name"];
                  }
               }
            }
            else {
               echo "Invalid file";
            }
    
        // EMAIL HEADERS
        $headers = 'From: '.$email_from."
    ".
        'Reply-To: '.$email_from."
    " .
        'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers); 
    ?>
    
    <!-- SUCCESS MESSAGE -->
    Your message has been sent.  Thank you for contacting me, I'll get back to you as soon as possible.
    
    <?php
    }
    ?>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?