0

I have the following PHP code which allows to enter details and upload a file. However, I want the script to execute even when no file is uploaded. I've referred to questions like How to check if user uploaded a file in PHP and How to test if a user has SELECTED a file to upload but didn't help me somehow. Please review my code and tell me where am I wrong. Thank you.

PHP File:

    <?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>";
}
}
?>

EDIT: Returns this error when I try to upload without a file (runs this part of the code)

else
  {

  die("<script>alert('Invalid file'); window.location.href='main.php';</script>");
  }
Community
  • 1
  • 1
Ayush Khemka
  • 480
  • 2
  • 9
  • 22
  • Does it return any error when you try to send without uploading any file? which error ? – Imane Fateh Aug 20 '13 at 11:18
  • oh i'm sorry not to mention that, it returns the error which i've set for an invalid file, which is 'Invalid file' inside the die command, I've updated it in my question. – Ayush Khemka Aug 20 '13 at 11:20
  • 1
    wrap everything related to handling files in this `if (count($_FILES) > 0){...}` – Dale Aug 20 '13 at 11:27
  • I would split that massive one liner (starting with: if ((($_FILES["file"]["type"] == "application/pdf")) into multiple statements so you can debug which part is not doing what you think. – Drew Aug 20 '13 at 11:29

2 Answers2

0
...

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

...
Jithin
  • 2,594
  • 1
  • 22
  • 42
0

The problem is with the if condition :

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

When the file doesn't exists or didn't get uploaded the else condition is executed which is die(..) so you have to treat the case when the file doesn't exists or didn't get uploaded apart by adding the following part of code :

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";
}

before this one :

else
   {
   die("<script>alert('Invalid file'); window.location.href='main.php';</script>");
   }
Imane Fateh
  • 2,418
  • 3
  • 19
  • 23