jane boe jane boe - 7 months ago 57
PHP Question

php undefined index with isset $_POST

trying to create a chat and keep getting Undefined index i've tried adding

? $_POST['chat'] : null;
but doesn't work

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


Line 8:

$sent = $_POST['chat'];


the variable is used here:

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>


Variables:

$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";


Edit: This is not a duplicate because this is for a very specific piece of code, i've also already used empty and I would not like to ignore the problem because it is a possible cause of another problem.

Thank you.

Answer

Use this code :

<?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 />';
    }
}
?>