1

在我的网站上,我有以下 HTML5 表单:

<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>

此 PHP 脚本正在处理的内容:

<!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.\n\n";

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

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

        // 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."\r\n".
    'Reply-To: '.$email_from."\r\n" .
    '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>

我在我的目录上创建了一个名为upload的文件夹,我相信这是脚本将文件上传到的位置。

当用户提交带有必填字段的表单时,信息会发送到我的电子邮件帐户。

但是,如果用户也想发送一个文件/文件,脚本不会处理这个,并且用户会在“您的消息已发送...... ”反馈 上方收到“无效文件”回显。

如果我然后转到我的电子邮件帐户,我可以看到信息已成功发送(即使出现“无效文件”错误),但用户上传的文件丢失并且不在我的上传文件夹中。

使用上面的脚本,我将如何实现文件上传部分?

谢谢你。

4

1 回答 1

2

好的..全新的答案。代码有一些问题。我让它在我的服务器上运行。

我现在不打算进行多文件上传。

<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>

所以,首先,将表格更改为

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

现在的脚本..

<!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

这不是 $_POST['uploads']。这是 $_FILES。从现在开始,您应该在脚本中使用 $uploads 值。

        $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.\n\n";

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

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

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

到这里为止一切都很好。你突然开始使用 $_FILES["file"],我假设是拼凑教程。此时 $_FILES["uploads"] 或 $uploads 均有效

        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)

这是一个非常小的图像。20000 字节只有 20kB。我猜你是从这里http://www.w3schools.com/php/php_file_upload.asp提取的。您可能想使用

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

对于 200kB 的图像,或

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

对于 2MB 图像

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

这是另一个问题。我将扩展 if 语句,使其更易于阅读。

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)

) 

您基本上说过,如果元数据用于 gif、png 或 jpg,并且小于 20kb,并且它是 Adob​​e Illustrator、Word 文档、图像、PDF 或 photoshop 文件

如果它是图像,那将是正确的。AI、PDF 或 DOC 永远不会通过上传类型检查。

           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."\r\n".
    'Reply-To: '.$email_from."\r\n" .
    '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>
于 2012-10-23T10:09:05.607 回答