[英]php undefined index with isset $_POST
嘗試創建聊天並保持獲取未定義索引,我嘗試添加? $_POST['chat'] : null;
? $_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";
編輯:這不是重復的,因為這是針對非常特定的一段代碼,我也已經使用了空白,並且我不想忽略該問題,因為這可能是另一個問題的原因。
謝謝。
您說您嘗試了三元條件,但沒有發布示例。 它看起來應該像這樣:
$sent = isset($_POST['chat']) ? $_POST['chat'] : null;
在PHP 7.0或更高版本中,您可以使用null合並運算符簡化此表達式:
$sent = $_POST['chat'] ?? null;
使用此代碼:
<?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 />';
}
}
?>
您提交表格了嗎?
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'] : '';
$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']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.