【问题标题】:Allow file upload field to be empty允许文件上传字段为空
【发布时间】:2013-08-22 10:01:42
【问题描述】:

我有以下 PHP 代码,允许输入详细信息并上传文件。但是,即使没有上传文件,我也希望脚本能够执行。我提到过How to check if user uploaded a file in PHP How to test if a user has SELECTED a file to upload 之类的问题 但并没有以某种方式帮助我。请检查我的代码并告诉我我哪里错了。谢谢。

PHP 文件

    <?php

require('PHPMailer/class.phpmailer.php');

if(isset($_POST['email'])) {

    // EDIT THE 2 LINES BELOW AS REQUIRED

    //$email_subject = "Request for Portfolio check up from ".$first_name." ".$last_name;

    $title = array('Title', 'Mr.', 'Ms.', 'Mrs.');
    $selected_key = $_POST['title'];
    $selected_val = $title[$_POST['title']]; 

    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required

  if(($selected_key==0))
    {

  die("<script>alert('Please enter your title'); window.location.href='main.php';</script>");
    }
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
     $email_message = "Name: ".$selected_val." ".clean_string($first_name)." ".clean_string($last_name)."<br />Email id: ".clean_string($email_from)."<br />Telephone no: ".clean_string($telephone)."<br />Details: ".clean_string($comments);
    $allowedExts = array("doc", "docx", "xls", "xlsx", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword")
|| ($_FILES["file"]["type"] == "application/excel")
|| ($_FILES["file"]["type"] == "application/vnd.ms-excel")
|| ($_FILES["file"]["type"] == "application/x-excel")
|| ($_FILES["file"]["type"] == "application/x-msexcel")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) && ($_FILES["file"]["size"] <= 20000)
|| file_exists($_FILES['file']['tmp_name']) || is_uploaded_file($_FILES['file']['tmp_name']) && in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] != 0)
    {
    echo "<script>alert('Error: " . $_FILES["file"]["error"] ."')</script>";
    }
  else
    {
        $d='upload/';
        $de=$d . basename($_FILES['file']['name']);
    $u=move_uploaded_file($_FILES["file"]["tmp_name"], $de);
$fileName = $_FILES['file']['name'];
    $filePath = $_FILES['file']['tmp_name'];
     //add only if the file is an upload
     //if($u)
     //echo "Uploaded!";
     }
  }
else
  {

  die("<script>alert('Invalid file'); window.location.href='main.php';</script>");
  }

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->IsSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug  = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host       = "***";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port       = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth   = true;
//Username to use for SMTP authentication
$mail->Username   = "***";
//Password to use for SMTP authentication
$mail->Password   = "***";
//Set who the message is to be sent from
$mail->SetFrom($email_from, $first_name.' '.$last_name);
//Set an alternative reply-to address
//$mail->AddReplyTo('replyto@example.com','First Last');
//Set who the message is to be sent to
$mail->AddAddress('***', '***');
//Set the subject line
$mail->Subject = 'Request for Portfolio Check up';
//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body
$mail->Body=$email_message;
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->AddAttachment($file);
$mail->AddAttachment($de);
//Send the message, check for errors
if(!$mail->Send()) {
  echo "<script>alert('Mailer Error: " . $mail->ErrorInfo."')</script>";
} else {
    $headers1 = 'From: ***'."\r\n".
'Reply-To: ritu@rsadvisories.com'."\r\n" .
'X-Mailer: PHP/' . phpversion();
   mail($email_from,'Re:Request for Portfolio Check up','We Have received your mail. We will contact you soon.',$headers1);
   echo "<script>alert('Your request has been submitted. We will contact you soon.');window.location.href='main.php';</script>";
}
}
?>

编辑:当我尝试在没有文件的情况下上传时返回此错误(运行这部分代码)

else
  {

  die("<script>alert('Invalid file'); window.location.href='main.php';</script>");
  }

【问题讨论】:

  • 当您尝试发送而不上传任何文件时是否返回任何错误?哪个错误?
  • 哦,很抱歉更不用说,它返回我为无效文件设置的错误,即 die 命令中的“无效文件”,我已经在我的问题。
  • 将与处理文件相关的所有内容都包装在这个if (count($_FILES) &gt; 0){...}
  • 我会把那个庞大的一个班轮(从:if ((($_FILES["file"]["type"] == "application/pdf")) 拆分成多个语句,这样你就可以调试哪个部分没有按照您的想法进行。

标签: php file-upload phpmailer


【解决方案1】:

问题在于 if 条件:

if (....|| file_exists($_FILES['file']['tmp_name']) || is_uploaded_file($_FILES['file']['tmp_name']) && in_array($extension, $allowedExts))

当文件不存在或未上传时,将执行 else 条件,即 die(..),因此您必须通过添加以下部分代码:

elseif (!(file_exists($_FILES['file']['tmp_name'])) || !(is_uploaded_file($_FILES['file']['tmp_name']))) 
{
echo "Warning : No file uploaded, Email will be sent without attachments";
}

在此之前:

else
   {
   die("<script>alert('Invalid file'); window.location.href='main.php';</script>");
   }

【讨论】:

    【解决方案2】:
    ...
    
    if(file_exists($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
        $allowedExts = array("doc", "docx", "xls", "xlsx", "pdf");
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);
        if ((($_FILES["file"]["type"] == "application/pdf")
        || ($_FILES["file"]["type"] == "application/msword")
        || ($_FILES["file"]["type"] == "application/excel")
        || ($_FILES["file"]["type"] == "application/vnd.ms-excel")
        || ($_FILES["file"]["type"] == "application/x-excel")
        || ($_FILES["file"]["type"] == "application/x-msexcel")
        || ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
        || ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) && ($_FILES["file"]["size"] <= 20000)
        || file_exists($_FILES['file']['tmp_name']) || is_uploaded_file($_FILES['file']['tmp_name']) && in_array($extension, $allowedExts))
            {
            if ($_FILES["file"]["error"] != 0)
              {
              echo "<script>alert('Error: " . $_FILES["file"]["error"] ."')</script>";
              }
              else
                  {
                  $d='upload/';
                  $de=$d . basename($_FILES['file']['name']);
                  $u=move_uploaded_file($_FILES["file"]["tmp_name"], $de);
                  $fileName = $_FILES['file']['name'];
                  $filePath = $_FILES['file']['tmp_name'];
                   //add only if the file is an upload
                   //if($u)
                   //echo "Uploaded!";
              }
        }
        else
        {
            die("<script>alert('Invalid file'); window.location.href='main.php';</script>");
        }
    }
    // create email headers
    $headers = 'From: '.$email_from."\r\n".
    
    ...
    

    【讨论】:

      猜你喜欢
      • 2022-09-26
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 2011-10-20
      • 1970-01-01
      相关资源
      最近更新 更多