你知道为什么我的代码没有进入我的else条件


Do you see why my code is not entering in my else condition?

我有一个表单,用于向新闻插入图像、标题、内容和图像库。

对于我的新闻的主图像和我的画廊图像,我想做一个关于选定的图像类型的验证。我只是想允许图像jpg, gif和png。如果用户发布了另一种类型的图像,我想显示一个错误消息,说'只接受JPG, PNG或GIF图像。'

但是我有一个问题,我的验证似乎正在工作,但是当我正确填写每个字段时,我没有进入我的其他条件来做我的插入。

我不进入这里:

else{
echo  'test'; // this test never appear
//here I have an insert but its not entering here
}

你知道问题出在哪里了吗?

我有了表单:

<form method="post" enctype="multipart/form-data">
    <div class="label">
        <span class="field">Title</span>
        <input type="text" name="titulo" />
    </div>         
     <div>
        <span>Main image:</span>
        <input type="file" name="img" accept="image/gif, image/jpg, image/jpeg, image/png" /> 
     </div>

     <div class="galerry">               
     <div>
         <span class="field">Gallery:</span>
         <input type="file" name="gb[]"  multiple="multiple" accept="image/gif, image/jpg, image/jpeg, image/png"  />       
        </div>  
    </div><!--/gallery-->
    <input type="submit" value="Insert" name="sendForm"/>
</form>

然后是php代码:

if(isset($_POST['sendForm'])){
    $f['title'] = $_POST['title'];
    $f['content'] =$_POST['content'];
    $img = $_FILES['img'];
    $extPerm = array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif');
    $gb = $_FILES['gb'];
    print_r($img);
    if(in_array('',$f) || empty($_FILES['img']['tmp_name'])){
        echo 'Please fill all fields';
    }
    else if(!in_array($img['type'],$extPerm)){
        echo 'Only JPG, PNG or GIF images are accepted.';
    }
    else if($_FILES['gb']['tmp_name'][0]){
        print_r($_FILES['gb']);
        $count= count($_FILES['gb']['tmp_name']);
        for($i=0;$i<$count;$i++){
        if(!in_array($gb['type'][$i],$extPerm)){
                echo 'Only JPG, PNG or GIF images are accepted.';
        }
        }
     } else {
        echo  'test'; // this test never appear
        //here I have an insert but its not entering here
    } 
}

对于这种情况,我会使用一个标志变量,比如$fine,像这样:

$fine = true;
if(in_array('',$f) || empty($_FILES['img']['tmp_name'])){
    echo 'Please fill all fields';
    $fine = false;
}
if(!in_array($img['type'],$extPerm)){
    echo 'Only JPG, PNG or GIF images are accepted.';
    $fine = false;
}
if($_FILES['gb']['tmp_name'][0]){
     print_r($_FILES['gb']);
     $count= count($_FILES['gb']['tmp_name']);
     for($i=0;$i<$count;$i++){
        if(!in_array($gb['type'][$i],$extPerm)){
            echo 'Only JPG, PNG or GIF images are accepted.';
            $fine = false;
        }
      }
 }
if($fine){//if there was no problem
   echo  'test'; // this test now should appear
   //here I have an insert but its not entering here
}

注意这里没有else语句,所以测试了所有可能的情况。这意味着您可能会出现多个错误。

您也可以将错误提交给$errors数组,然后测试if(count($errors) == 0),例如