Search code examples
phpif-statementisset

PHP check if isset one of the two


I am trying to check both inputs but when only one of the two is set it should give TRUE. when both are empty it should give a error.

      //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'];
           

Tried multiple things but it doesnt want to work as i want.


Solution

  • One alternative (and cleaner IMHO) is to do your validation upfront and then process it once you know you have valid data.

    When you start processing, you'll also need to check which source your need to process - $_FILE Vs. $_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
        }
    }