doujiepin5547 2017-03-16 14:42
浏览 68
已采纳

来自php脚本的Json响应不起作用

I'm building a form to upload images and other data and I want it to return json validation or success response via the ajax success function.

Problem is the php script seems to do some of the if statements, but then completely ignores the extensions validation statement and the file size validation.

I have a switch/case statement in the AJAX to handle the json response from the php script. the switch/case statement then shows the respective message and then fades out.

note: No errors were found in the console.

Thank you for any help.

AJAX:

$(document).ready(function (e) {
    $('.add_business_form').on('submit',(function(e) {  

        e.preventDefault();

        var formData = new FormData(this);


        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            dataType: "json",
            success:function(response){

    switch(response.message){
      case 'logo_success': 
         logoSuccess();
      break;
      case 'file_is_not_image': 
        file_is_not_image();
      break;
      case 'No_file_selected': 
        No_file_selected();
      break;        

      case 'wrong_logo_extention':
        Wrong_extention();
      break;        
       case 'logo_too_big':
        logo_too_big();
      break;
       case 'unknown_error':
        unknown_error();
      break;
    }           

            },
            error: function(data){   


            }
        });
    }));

}); 

jQuery functions(to handle ajax response):

<script>
 function logoSuccess(){
 $('.response_success').fadeIn('fast').delay(10000).fadeOut('fast');    
$('.add_business_form')[0].reset();  
 }      
</script>   
<script>
 function file_is_not_image(){
 $('.file_is_not_image').fadeIn('fast').delay(10000).fadeOut('fast');    
 }      
</script>
<script>
 function No_file_selected(){
 $('.No_file_selected').fadeIn('fast').delay(10000).fadeOut('fast');         
 }      
</script>
<script>
 function logo_too_big(){
 $('.logo_too_big').fadeIn('fast').delay(10000).fadeOut('fast');         
 }      
</script>
<script>
 function unknown_error(){
 $('.unknown_error').fadeIn('fast').delay(10000).fadeOut('fast');        
 }      
</script>

PHP script

if(empty($_FILES['uploaded_img_preview']['name'])){
    $response["message"] = 'No_file_selected';
}else{

$imgFile = $_FILES['uploaded_img_preview']['name'];
$tmp_dir = $_FILES['uploaded_img_preview']['tmp_name'];
$imgSize = $_FILES['uploaded_img_preview']['size'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$upload_dir = '../images/'; // upload directory


   // valid image extensions
   $valid_extensions = array('jpg','png','jpeg'); // valid extensions

   // rename uploading image
   $new_logo_name = rand(1000,1000000).".".$imgExt;

   // allow valid image file formats
   if(in_array($imgExt, $valid_extensions)){   
    // Check file size '5MB'
    if($imgSize < 500000)    {

    }
    else{
     $response["message"] = 'logo_too_big';
    }
   }
   else{
     $response["message"] = 'wrong_logo_extention';  
   }

    if (move_uploaded_file($tmp_dir,$upload_dir.$new_logo_name)){
     $response["message"] = 'logo_success'; 
    }else{
    $response["message"] = 'unknown_error'; 

    }
 }

echo json_encode($response);
exit();
  • 写回答

1条回答 默认 最新

  • dora0817 2017-03-16 15:39
    关注

    The reason that the images are uploading when, the file size is large and also when the ext is wrong, is simple because, you are allowing your script to upload even if the errors exists, what you need is to have an error counter variable so that when the error occurs you increment the variable then only upload the image when the error counter is zero

    here how :

    <?php
    
    $errors = "";//Count error
    if (empty($_FILES['uploaded_img_preview']['name'])) {
        $response["message"] = 'No_file_selected';
    } else {
    
        $imgFile    = $_FILES['uploaded_img_preview']['name'];
        $tmp_dir    = $_FILES['uploaded_img_preview']['tmp_name'];
        $imgSize    = $_FILES['uploaded_img_preview']['size'];
        $imgExt     = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION));
        $upload_dir = '../images/'; // upload directory
    
    
        if ($imgExt != "jpg" && $imgExt != "png" && $imgExt != "jpeg" && $imgExt != "gif") {
            $response["message"] = 'wrong_logo_extention';
    
            $errors++; //increment
        }
    
        if ($imgSize > 500000) {
    
            $response["message"] = 'logo_too_big';
            $errors++; //increment
        }
        // rename uploading image
        $new_logo_name = rand(1000, 1000000) . "." . $imgExt;
    
        //upload only if there are no errors
        if ($errors <= 0) {
    
            if (move_uploaded_file($tmp_dir, $upload_dir . $new_logo_name)) {
                $response["message"] = 'logo_success';
            } else {
                $response["message"] = 'unknown_error';
    
            }
    
        }
    
    
    }
    
    echo json_encode($response);
    exit();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog