dpj997991 2018-05-02 20:22
浏览 70
已采纳

对于html表单输入,PHP总是将$ _POST数组isset /!empty / sizeof> 0评估为true

I have a basic form to upload an image:

<?php
  if(!empty($_POST['?upload_img'])) {
      echo "true<br>";
  } else { echo "false<br>"; }
?>

<html>
  <form action='' method='post' enctype='multipart/form-data'>
    <input type='file' name='input_img' id='input_img'><br>
    <input type='submit' value='Upload Image' name='?upload_img'>
  </form>
</html>

I would like a PHP boolean/evaluation pair to run only once for each upload.

I have tried evaluating using !empty,isset,sizeof(foo)>0

I have also tried to find a solution using $_SESSIONs

Is there are correct use of unset or $_POST=array()/$_FILE=array() that I have missed?

I can achieve the desired behaviour with sessions:

<?php
  session_start();
  if(!empty($_SESSION['foo'])) {
    echo "true<br>";
  } else { echo "false<br>"; }
?>

<html>
  <?php
    if(!sizeof($_SESSION['foo'])) {
      $_SESSION['foo']=array();
      $_SESSION['foo']['bar']="path/to/the/file.png";
    } else { $_SESSION=array(); }
  ?>
</html>

How can I achieve the same with input from a <form> instead?

Any help is much appreciated!

  • 写回答

2条回答 默认 最新

  • duanjiaonie6097 2018-05-05 00:39
    关注

    For completeness, an outline approach specific to my issue:

    <!--filename:foo.php-->
    <?php
      session_start();
      if(isset($_POST['?confirm'])) {
        $_SESSION['input']=$_FILES['input'];
        header("HTTP/1.1 303");
        header("Location: http://$_SERVER[HTTP_HOST]/foo.php");
        die;
      } else if(!empty($_SESSION['input'])) {
        echo "true<br>";
        session_unset();
        session_destroy();
      } else { echo "false<br>"; }
    ?>
    <html>
      <form action='foo.php' method='post' enctype='multipart/form-data'>
        <input type='file' name='input' id='input'><br>
        <input type='submit' value='confirm' name='?confirm'>
      </form>
    </html>
    

    Based on Post-Redirect-Get Pattern in PHP

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据