【问题标题】:PHP check if isset one of the two [duplicate]PHP检查isset是否是两者之一[重复]
【发布时间】:2020-12-08 02:17:03
【问题描述】:

我正在尝试检查两个输入,但是当仅设置两个输入中的一个时,它应该为 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'];
           

尝试了多种方法,但它不想按我的意愿工作。

【问题讨论】:

  • 你试过||(或)吗?
  • 这能回答你的问题吗? How to check if any fields in a form are empty
  • 您有 2 个相互干扰的 if 语句。删除您的第一个 if 语句并使用 ||(或)。
  • 试试if (isset($_FILES['post_image']) || isset($pyturl)) {...
  • @waterloomatt 这会在设置 2 个之一时导致错误。

标签: php if-statement isset


【解决方案1】:

另一种选择(恕我直言,更简洁)是预先进行验证,然后在您知道自己拥有有效数据后进行处理。

当您开始处理时,您还需要检查您需要处理的来源 - $_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
    }
}

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2020-03-27
    • 2011-04-17
    相关资源
    最近更新 更多