0

I am creating a chat website where people put their text into a input box and then it appears inside a chatbox. I'm trying to do this by turning the usertext into a session variable and then echoing that session variable into the chatbox div. This however, gives me an Undefined index error.

Here is my code for page2.php

<!DOCTYPE html>
<?php

session_start();

if(isset($_POST["submitusername"])) {



}else {

header("Location:page1.php");

}

?>

<html lang="en-US">

<head>

<title>meekochat</title>
<link rel="icon" href="icon.png">
<link rel="stylesheet" type="text/css" href="style.css">

<?php

if(isset($_POST["submitusername"])) {

$_SESSION["username"] = $_POST["username"];

}
if(isset($_POST["submitusertext"])) {

$_SESSION["usertext"] = $_POST["usertext"];

}

?>

<style>


</style>

</head>


<body id="body">

<div id="wrapper">
<br><br>
<center><div id="chatbox"><?php echo $_SESSION["usertext"]; ?></div>
<br>

<form action="page2.php" method="post">
<input type="text" id="usertext" name="usertext" placeholder="Type 
Something">
<input type="submit" id="submitusertext" name="submitusertext" value="Send">


</form><br><br></center>


</div>


</body>

</html>
koolaidguy
  • 31
  • 6
  • The first time you load this page `$_SESSION["usertext"]` will not be set. So you need to have a check for that in this code `?php echo $_SESSION["usertext"]; ?>` – Nick Mar 23 '19 at 02:31
  • @koolaidguy maybe (not) but thats one of the issues with the code, session wont hold so its going to fail once you fix the undefined index, which it marked appropriately as a dupe.. – Lawrence Cherone Mar 23 '19 at 02:39

1 Answers1

0

You need to change <?php echo $_SESSION["usertext"]; ?> to <?php echo $_SESSION["usertext"] ?? ''; ?> because the first time when you land on this page, the $_SESSION["usertext"] will not have been initialized. It will be set only after submitting the form.

asiby
  • 3,229
  • 29
  • 32