0

Okay, so my code to validate the user and log them into their account. My code for user validation is a separate file with no HTML, just PHP. It then echo either true or false to my homepage, which if true, will redirect them to the main page while a user logged in. My login file is as follows:

while ($row = mysql_fetch_array($res)){ 
if ($row['password'] == $pass){
echo "true";
session_start();
$_SESSION["username"] = $user;
} else {
echo "false";
}
}

If the code echos true, the javascript code will redirect them using window.location. On the page they get too, home.php, the PHP code (not html) looks like this:

<?php session_start(); ?>
<script>
var ses = "<?php echo $_SESSION["username"]; ?>";
console.log(ses);
</script>

For some reason, it logs nothing. It still logs, but it logs a blank variable. If anyone could help, that would be amazing! Thank you.

Trevor Judice
  • 137
  • 1
  • 1
  • 10
  • where is the $user variable ? $_SESSION['username'] = $row; – Onur Feb 23 '16 at 20:41
  • Above. I didnt include the rest of the file, but it is a variable, as the login does work, but the session variables do not stay. I also tried it with "hey" instead of $user, and still no luck – Trevor Judice Feb 23 '16 at 20:44
  • you must use session_start before while – Onur Feb 23 '16 at 20:45
  • Why do you have a `while` loop? Can the query return multiple rows for the same user? Won't that make you echo `truetrue` if there are two rows? – Barmar Feb 23 '16 at 20:47

1 Answers1

0

You need to move the echo statement. You can't have any output before session_start(). So it should be:

session_start();
echo "true";

See How to fix "Headers already sent" error in PHP

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612