PHP检查isset是否为两者之一

问题描述

我正在尝试检查两个输入,但是当仅设置两个输入中的一个时,它应该为TRUE。 当两者都为空时,应该给出一个错误

      //check if post image upload or youtube url isset
      $pyturl = $_POST['post_yturl'];
      if (isset($_FILES['post_image']) && isset($pyturl)) {     
        if (empty($_FILES['post_image']['name']) or empty($pyturl)) {
          $errors = '<div class="error2">Choose a news header.</div>';

         } else {   
          //check image format                                                                                                    
           $allowed = array('jpg','jpeg','gif','png'); 
           $file_name = $_FILES['post_image']['name']; 
           $file_extn = strtolower(end(explode('.',$file_name)));
           $file_temp = $_FILES['post_image']['tmp_name'];
           

尝试了很多事情,但它并不想像我想要的那样工作。

解决方法

另一种方法(和更清洁的IMHO)是先进行验证,然后在知道有效数据后进行处理。

开始处理时,还需要检查需要处理的源-$_FILE与。 $_POST

<?php

$isValid = true;

// Validation - if both sources are empty,validation should fail. 
if (!isset($_FILES['post_image']) && !isset($_POST['post_yturl'])) {
    $isValid = false;
    $errors = '<div class="error2">Choose a news header.</div>';
}

... More validation if needed

if ($isValid) {

    // At this point you know you have at least 1 source. Start processing. 

    if (isset($_FILES['post_image']) {
        ... do your processing
    }

    if (isset($_POST['post_yturl']) {
        ... do your processing
    }
}