php未定义的索引与isset$_POST


php undefined index with isset $_POST

尝试创建聊天并不断获取未定义索引我尝试添加? $_POST['chat'] : null;,但不起作用

注意:Undefined index: chat in /Applications/MAMP/htdocs/chat/chat.php on line 8

第8行:

$sent = $_POST['chat'];

这里使用的变量是:

if (isset($_POST['chat'])) {
    if (!empty($sent)) {
        fwrite($myfile, $first.': '.$txt.'=');
        fclose($myfile);
    } else if (empty($sent)) {
        if(isset($_POST['chat'])){
            echo 'Cant send an empty message','<br />';
        }
    }
}

HTML:

<body>
    <iframe id='reload' src='refresh.php'>
        <fieldset class="field">
                <div id="list"><p><?php
                    $filename = 'chat.txt';
                    $handle = fopen($filename, 'r');
                    $detain = fread($handle, filesize($filename));
                    $chat_array = explode('=', $detain);
                    foreach($chat_array as $chat) {
                        echo $chat.'<br />';
                    }
                    ?></p></div>
        </fieldset>
    </iframe>
    <form action="chat.php" method="POST">
        <input type="text" name="chat" class="textbox">
        <input type="submit" value="Send" class="button">
    </form>
</body>

变量:

    $sent = $_POST['chat'];
    $myfile = fopen("chat.txt", 'a') or die("Unable to open file!");
    $txt = ($sent."'n");
    $first = getuserfield('username');
    $active = ($first.":".$ip_addr);
    $activef = fopen("ip-user.txt", 'a');
    $myFile = "domains/domain_list.txt";

编辑:这不是重复的,因为这是针对一段非常特定的代码,我也已经使用了空,我不想忽略这个问题,因为这可能是另一个问题的原因。

谢谢。

使用此代码:

<?php 
$sent = '';
if(isset($_POST['chat'])) 
{
    $sent = $_POST['chat'];
    if (!empty($sent))
    {
        $txt = ($sent."'n");
        fwrite($myfile, $first.': '.$txt.'=');
        fclose($myfile);
    } 
    else 
    {
        echo 'Cant send an empty message','<br />';
    }
}
?>

您说您尝试了三元条件,但没有发布您尝试的示例。它应该是这样的:

$sent = isset($_POST['chat']) ? $_POST['chat'] : null;

在PHP7.0或更高版本中,您可以使用null联合运算符来简化此表达式:

$sent = $_POST['chat'] ?? null;

您提交了表格吗?

PHP:

if (isset($_POST['chat'])) {
if (!empty($sent)) {
    fwrite($myfile, $first.': '.$txt.'=');
    fclose($myfile);
} else if (empty($sent)) {
    if(isset($_POST['chat'])){
        echo 'Cant send an empty message','<br />';
    }
}

}

HTML:

<form action="" method="POST">
    <input type="text" name="chat">
    <input type="submit" name="submit">
</form>

执行类似$sent = isset($_POST['chat']) ? $_POST['chat'] : ''; 的操作

顺便说一下:你的代码有很多冗余。

if (isset($_POST['chat'])) {
  if (!empty($sent)) {
    fwrite($myfile, $first.': '.$txt.'=');
    fclose($myfile);
  } else {
    echo 'Cant send an empty message','<br />';
  }
}

如果你不想每次都写一个isset()条件,你可以定义一个简短的函数:

function get(&$var, $default = null)
{
  return isset($var) ? $var : $default;
}

这样使用:

$sent = get($_POST['chat'], '');

或者只是

$sent = get($_POST['chat']);