猿问

PHP 检查是否设置两者之一

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

           

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


慕桂英546537
浏览 87回答 1
1回答

一只甜甜圈

一种替代方案(恕我直言,更干净)是预先进行验证,然后在知道拥有有效数据后对其进行处理。当您开始处理时,您还需要检查需要处理的来源 -$_FILE与。$_POST<?php$isValid = true;// Validation - if both sources are empty, validation should fail.&nbsp;if (!isset($_FILES['post_image']) && !isset($_POST['post_yturl'])) {&nbsp; &nbsp; $isValid = false;&nbsp; &nbsp; $errors = '<div class="error2">Choose a news header.</div>';}... More validation if neededif ($isValid) {&nbsp; &nbsp; // At this point you know you have at least 1 source. Start processing.&nbsp;&nbsp; &nbsp; if (isset($_FILES['post_image']) {&nbsp; &nbsp; &nbsp; &nbsp; ... do your processing&nbsp; &nbsp; }&nbsp; &nbsp; if (isset($_POST['post_yturl']) {&nbsp; &nbsp; &nbsp; &nbsp; ... do your processing&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答