2016-05-30 7 views
0

私は、ユーザーがファイルをアップロードすることを選択できるフォームを持っており、添付ファイルとして電子メールを送信します。添付ファイルなしのPHPフォームエラー

私が抱えている問題は、添付ファイルを選択しなくても、以下のAJAXアラートが常にPHPコードのThe uploaded file is not a supported file type.メッセージを表示するということです。

if (data.error) { 
    alert(data.error.message); 
}` 

AJAXコード:

$(document).ready(function (e){ 
$("#main-contact-form").on('submit',(function(e){ 
    e.preventDefault(); 
    $('#sendingemail').fadeIn(); 
     $.ajax({ 
     url: "../sendemail.php", 
     type: "POST", 
     data: new FormData(this), 
     contentType: false, 
     cache: false, 
     processData: false, 
     success: function(data){ 
      if (data.error) { 
        alert(data.error.message); 
       } 
      else{ 
       $('#sendingemail').fadeOut(); 
       $('#emailsent').fadeIn(); 
       alert(data.message); 
      } 
     }, 
     error: function(XHR,textStatus,errorThrown) { 
       console.log(data); 
      //alert("error"); 
       alert(XHR.status); 
      alert(textStatus); 
      alert(errorThrown); 
     } 
    }   
); 
})); 
}); 

PHPコード:

<?php 

    header('Content-type: application/json'); 

      // WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE. 
      // WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT: 
      $status = array(
          'type'   =>'Error', 
          'message'  =>'Couldn\'t send the Email at this Time. Something went wrong', 
          'attachement' =>'Couldn\'t attach the uploaded File to the Email.' 
      ); 

    //Added to deal with Files 
    require_once('PHPMailer/class.phpmailer.php'); 

    if(isset($_FILES['uploaded_file'])){  
    //Get the uploaded file information 
     $name_of_uploaded_file = 
      basename($_FILES['uploaded_file']['name']); 

     //get the file extension of the file 
     $type_of_uploaded_file = 
      substr($name_of_uploaded_file, 
      strrpos($name_of_uploaded_file, '.') + 1); 

     $size_of_uploaded_file = 
      $_FILES["uploaded_file"]["size"]/1024;//size in KBs 

     //Settings 
     $max_allowed_file_size = 10000; // size in KB 
     $allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png"); 

     //Validations 
     if($size_of_uploaded_file > $max_allowed_file_size) 
     { 
      $status['type'] = 'Error'; 
     $status['message'] = 'Error: Size of file should be less than ~10MB. The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.'; 
      echo(json_encode($status)); 
      exit; 
     } 

     //------ Validate the file extension ----- 
     $allowed_ext = false; 
     for($i=0; $i<sizeof($allowed_extensions); $i++) 
     { 
      if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0) 
      { 
       $allowed_ext = true; 
      } 
     } 

     if(!$allowed_ext) 
     { 
      $status['type'] = 'Error'; 
     $status['message'] = 'Error: The uploaded file is not a supported file type.'; 
      echo(json_encode($status)); 
      exit; 
     } 

    $upload_folder = "temp/"; 
     $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; 
     $tmp_path = $_FILES["uploaded_file"]["tmp_name"]; 

     if(is_uploaded_file($tmp_path)) 
     { 
      if(!copy($tmp_path,$path_of_uploaded_file)) 
      { 
       $status['type'] = 'Error'; 
      $status['message'] = 'Error: Encountered an error while copying the uploaded file'; 
      exit; 
      } 
     } 
} 
    //--end 

    $name = @trim(stripslashes($_POST['name'])); 
    $clientemail = @trim(stripslashes($_POST['email'])); 
    $subject = @trim(stripslashes($_POST['subject'])); 
    $message = @trim(stripslashes($_POST['message'])); 

    $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message; 

    $email = new PHPMailer();  

    $email->From  = $clientemail; 
    $email->FromName = $name; 
    $email->Subject = $subject; 
    $email->Body  = $body; 
    $email->AddAddress('[email protected]'); //Send to this email 

    $email->isMail(); 

    if(isset($_FILES['uploaded_file'])){ 
       if($email->AddAttachment($path_of_uploaded_file , $name_of_uploaded_file)){ 
      $status['message'] = 'The Uploaded File was successfully attached to the Email.'; 
     } 
    } 
     header("Content-Type: application/json; charset=utf-8", true); 
// NOW, TRY TO SEND THE EMAIL ANYWAY: 
     try{ 
      $success = $email->send(); 
      $status['type'] = 'success'; 
      $status['message'] = 'Thank you for contacting us. We will reply as soon as possible.'; 
     }catch(Exception $e){ 
      $status['type']  ='Error'; 
      $status['message'] ='Couldn\'t send the Email at this Time. Something went wrong';  
     } 

die(json_encode($status)); 

HTML:

 <form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" enctype="multipart/form-data"> 
      <div class="col-sm-5 col-sm-offset-1"> 
       <div class="form-group"> 
        <label>Name *</label> 
        <input type="text" name="name" class="form-control" required="required"> 
       </div> 
       <div class="form-group"> 
        <label>Email *</label> 
        <input type="email" name="email" class="form-control" required="required"> 
       </div> 
       <div class="form-group"> 
        <label>Phone</label> 
        <input type="number" class="form-control"> 
       </div> 
       <div class="form-group"> 
        <label>Company Name</label> 
        <input type="text" class="form-control"> 
       </div>       
      </div> 
      <div class="col-sm-5"> 
       <div class="form-group"> 
        <label>Subject *</label> 
        <input type="text" name="subject" class="form-control" required="required"> 
       </div> 
       <div class="form-group"> 
        <label>Message *</label> 
        <textarea name="message" id="message" required="required" class="form-control" rows="8" style="height:125px"></textarea> 
        <label for='uploaded_file' style="margin-top:10px">Select A Photo To Upload:</label> 
        <input type="file" name="uploaded_file"> 
       </div>       
       <div class="form-group"> 
        <button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button> 
       </div> 
      </div> 
     </form> 
+0

アップロードするファイルの種類はわかりますか? –

答えて

1

ときにprint_r($_FILES)あなたはAを添付していない場合でも、わかりますファイル、wil lはあなたにこの配列を与える:

Array 
(
    [uploaded_file] => Array 
     (
      [name] => 
      [type] => 
      [tmp_name] => 
      [error] => 4 
      [size] => 0 
     ) 
) 

あなたは

  1. $_FILES['uploaded_file']['error'] == 0または
  2. !empty($_FILES['uploaded_file']['name'])

EDIT場合、むしろisset($_FILES['uploaded_file'])をチェックするが、したくない:

ちょうど私は明確です、私の答えは、あなたがエラーメッセージを受け取ったというコメントに対処しています "...添付ファイルを選択しなかったとしても"。私の答えは、なぜこれが起こるのかを説明します。

+0

Badrushはファイル形式を制限しています。そのコードにエラーはありません。 –

+1

@Raj_King OPは、エラーが発生していると言っています。「エラー:アップロードされたファイルは、サポートされているファイルタイプではありません。彼らはもちろん、フォームを提出するときに、 '$ _FILES'配列がセットされているかどうかだけチェックしています。デフォルトでは(常に「true」になる)ため、拡張子は存在しません。したがって、ファイルが添付されていないときは常にそれが表示されます。 – Rasclatt

+0

彼はファイルの拡張子を検証しています。彼の制限されたフォーマットと拡張が一致しない場合、彼は "エラー:アップロードされたファイルはサポートされているファイルタイプではありません。"というエラーを投げます。 それは次のコードによってスローされるカスタムエラーメッセージです。 'if(!$ allowed_ext){ $ status ['type'] = 'エラー'; $ status ['message'] = 'エラー:アップロードされたファイルはサポートされているファイルタイプではありません。'; echo(json_encode($ status)); exit; ' このコード以外は' jpg jpeg gif bmp png'の形式を使用しています –

関連する問題