2016-05-26 3 views
0

У меня есть PHP, который принимает входные данные из формы и отправляет ее в виде электронной почты. Однако, если файл не прикреплен, я получаю следующие ошибки:PHP - Обработка формы, когда файл не загружен

Как с этим справиться?

Ошибки:


Примечание: Undefined индекс: uploaded_file в F: \ CL2 \ sendemail.php на линии

Примечание: Undefined индекс: uploaded_file в F: \ CL2 \ sendemail.php on line

Примечание: неопределенная переменная: ошибки в F: \ CL2 \ sendemail.php на линии

Примечание: Undefined индекс: uploaded_file в F: \ CL2 \ sendemail.php на line
{"type": "success", "message": "Спасибо, что свяжитесь с нами. Как можно раньше мы с вами «» прикрепленного «:» Не удалось присоединить загруженный файл к электронной почте "}

Мой HTML код:.

<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php"> 
      <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> 

Мой Jquery код:

// Contact form 
var form = $('#main-contact-form'); 
form.submit(function(event){ 
    event.preventDefault(); 
    var form_status = $('<div class="form_status"></div>'); 
    $.ajax({ 
     url: $(this).attr('action'), 

     beforeSend: function(){ 
      form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn()) 
     }, 
     data: $(this).serialize(); 
    }).done(function(data){ 
     form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut(); 
    }); 
}); 

Мой PHP код:

<?php 
// ini_set('display_errors', 'On'); 
// error_reporting(E_ALL); 
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');\ 

//  require_once('/PHPMailer/class.smtp.php'); 
//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 = 10240; // size in KB 
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png"); 

//Validations 
if($size_of_uploaded_file > $max_allowed_file_size) 
{ 
    $errors .= "\n Size of file should be less than $max_allowed_file_size (~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."; 
} 

//------ 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) 
{ 
    $errors .= "\n The uploaded file is not supported file type. ". 
    " Only the following file types are supported: ".implode(',',$allowed_extensions); 
} 

//copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission 
$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)) 
    { 
    $errors .= '\n error while copying the uploaded file'; 
    } 
} 
//--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 

// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION  
$email->isMail(); 

// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE: 
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT 
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY... 
if($email->AddAttachment($path_of_uploaded_file , $name_of_uploaded_file)){ 
    $status['attachment'] = 'Uploaded File was successfully attached to the Email.'; 
} 

// NOW, TRY TO SEND THE EMAIL ANYWAY: 
try{ 
    $success = $email->send(); 
    $status['type']  = 'success'; 
    $status['message'] = 'Thank you for contact us. As early as possible we will contact you.'; 
}catch(Exception $e){ 
    $status['type']  ='Error'; 
    $status['message'] ='Couldn\'t send the Email at this Time. Something went wrong';  
} 

// SIMPLY, RETURN THE JSON DATA... 
die (json_encode($status)); 
+0

Это лучший матч дубликата вопрос: http://stackoverflow.com/questions/946418/how-to-check-if-user-uploaded-a- file-in-php –

ответ

2

проверка первых, если $_FILES['uploaded_file']['name'] пуст, а затем распечатать дружественную ошибку сообщение, если не на вашей странице PHP:

<?php 
// ini_set('display_errors', 'On'); 
// error_reporting(E_ALL); 
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');\ 

//  require_once('/PHPMailer/class.smtp.php'); 





if (!empty($_FILES['uploaded_file']['name'])){ 


//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 = 10240; // size in KB 
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png"); 

//Validations 
if($size_of_uploaded_file > $max_allowed_file_size) 
{ 
    $errors .= "\n Size of file should be less than $max_allowed_file_size (~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."; 
} 

//------ 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) 
{ 
    $errors .= "\n The uploaded file is not supported file type. ". 
    " Only the following file types are supported: ".implode(',',$allowed_extensions); 
} 

//copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission 
$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)) 
    { 
    $errors .= '\n error while copying the uploaded file'; 
    } 
} 
} // end if (!empty($_FILES['uploaded_file']['name'])) 
//--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 

// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP BUILT IT MAIL FUNCTION  
$email->isMail(); 

// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE: 
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT 
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY... 
if($email->AddAttachment($path_of_uploaded_file , $name_of_uploaded_file)){ 
    $status['attachment'] = 'Uploaded File was successfully attached to the Email.'; 
} 

// NOW, TRY TO SEND THE EMAIL ANYWAY: 
try{ 
    $success = $email->send(); 
    $status['type']  = 'success'; 
    $status['message'] = 'Thank you for contact us. As early as possible we will contact you.'; 
}catch(Exception $e){ 
    $status['type']  ='Error'; 
    $status['message'] ='Couldn\'t send the Email at this Time. Something went wrong';  
} 

// SIMPLY, RETURN THE JSON DATA... 
die (json_encode($status)); 
+0

Хорошо, поэтому, когда я добавляю этот код, я получаю «нет загруженного файла», за исключением того, что, когда не выбран ни один файл, я все еще хочу отправить электронное письмо ... – Badrush

+1

@Badrush Я отредактировал свой ответ, чтобы обернуть 'if 'вокруг процесса загрузки файла. Вы должны изменить свой вопрос, чтобы включить это требование. –

+0

Я закончил использование 'if (isset ($ _ FILES ['uploaded_file'] ['name']))' и это сработало, но когда я пытаюсь прикрепить файл, он не привязан ... никаких идей? Я использую XAMPP и Mercury (электронная почта настроена правильно). У меня есть локальная папка под названием temp, которую я должен добавить в приложение, прежде чем присоединяться к электронной почте. Кроме того, следующие строки также необходимо, если заявление .. 'если ($ email-> AddAttachment ($ path_of_uploaded_file, $ name_of_uploaded_file)) {$ статус [ 'вложение'] =«Загруженный файл был успешно присоединен к Эл. адрес.'; } ' – Badrush

Смежные вопросы