【问题标题】:igoring condition during submit form in PHP在PHP中提交表单期间忽略条件
【发布时间】:2018-11-25 06:21:32
【问题描述】:

我正在尝试在我的表单提交中设置一个条件。我想检查我的任何字段中没有任何空值。在我的表单中,我有两个文本区域和一个文件上传部分。

我提出了如下条件

if (($_POST['question'] != "") AND ($_POST['answer'] != "") AND ($_FILES['picture_name']['name'] != "")) {
echo "ok";
}
else {
echo "field empty";
}

如果文件上传或问题为空,但它的接受和回显即使答案为空,它也会给出错误。让我知道我的情况是否有任何问题。 谢谢

【问题讨论】:

  • 您能否也发布导致调用此 PHP 代码的相应 HTML 代码?
  • 嗨!对不起!我的文本区域中有空间,因此我们无法将其检测为空。
  • 所以基本上你在结尾或开头有一些额外的空格导致了问题?如果是这样,那么您应该在检查之前修剪字符串。见this链接

标签: php


【解决方案1】:

这可能会有所帮助...

if (!empty($_POST['question']) && !empty($_POST['answer']) && is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo "ok";
}
else {
echo "field empty";
}

【讨论】:

【解决方案2】:

我发现最好在继续处理代码之前检查并消除所有问题。希望这能让您走上正确的轨道,了解可能会或可能不会按计划进行的事情。

<?php

$problems = array();
// Check the obvious first.
if (empty($_POST) || empty($_FILES)) {
  if (empty($_POST)) {
    $problems[] = 'POST empty';
  }
  if (empty($_FILES)) {
    $problems[] = 'FILES empty';
  }
}
// If those tests passed, proceed to check other details
else {
  // Check if the array keys are set
  if (!isset($_POST['question']) || !isset($_POST['answer'])) {
    if (!isset($_POST['question'])) {
      $problems[] = 'Question not set';
    }
    if (!isset($_POST['answer'])) {
      $problems[] = 'Answer not set';
    }
  }
  else {
    // If those tests passed, check if the values are an empty string.
    if ($_POST['question'] == "" || $_POST['answer'] == "") {
      if ($_POST['question'] == "") {
        $problems[] = 'Question empty';
      }
      if ($_POST['answer'] == "") {
        $problems[] = 'Answer empty';
      }
    }
  }

  // There are many ways to eliminate problems... The next few lines
  // are slightly different since they use elseif conditions (meaning
  // only one of them will be displayed, if any).
  if (!isset($_FILES['picture_name'])) {
    $problems[] = 'Picture name not set';
  }
  elseif (empty($_FILES['picture_name'])) {
    $problems[] = 'Picture name empty';
  }
  elseif (!isset($_FILES['picture_name']['name'])) {
    $problems[] = 'Picture filename not set';
  }
  elseif (empty($_FILES['picture_name']['name'])) {
    $problems[] = 'Picture filename empty';
  }
}

// If $problems array is still empty, everything should be OK
if (empty($problems)) {
  $outcome = 'OK';
}
// If $problems array has values, glue them together and display
// each one on a new line
else {
  $outcome = implode(PHP_EOL, $problems);
}

echo $outcome;

【讨论】:

    猜你喜欢
    • 2013-12-20
    • 1970-01-01
    • 2017-11-01
    • 2015-05-20
    • 2011-07-12
    • 1970-01-01
    • 2011-12-18
    • 2015-05-10
    • 1970-01-01
    相关资源
    最近更新 更多