-1

So in 'index.php' the user puts their username and password into HTML inputs and it saves them to '$username' and '$password'. Then the PHP says:

<?php
$loginquery = mysqli_query($connection,"SELECT * FROM users WHERE username = '$username' AND password = '$password'");
$user = mysqli_fetch_array($loginquery);
session_start();
$_SESSION['username'] = $user['username'];
echo $_SESSION['username'];
?>

It echo's out '$_SESSION['username']' alright but if I then go to 'home.php' it hasn't actually saved the variable and it says 'Notice: Undefined variable: _SESSION in /Applications/XAMPP/xamppfiles/htdocs/tobyscott/home.php on line 24'

This is REALLY bugging me! Thanks :)

Toby Scott
  • 79
  • 7
  • How is `home.php` related to `index.php`? does `index.php` include `home.php`? If not: is there a `session_start();` in `home.php`? – WcPc Mar 05 '16 at 21:59
  • 1
    Please post the relevant code of home.php. In all likelihood, it is missing `session_start()`, which must be called on every script that accesses the session (and before any output is generated) – Michael Berkowski Mar 05 '16 at 21:59

2 Answers2

1

Do you have a session_start(); statement in your home.php as well - or is it missing there?

Reto
  • 1,305
  • 1
  • 18
  • 32
0

Sounds like you're using a script that submits to itself.

Add a conditional to ensure that form handling logic is ran only on get/post submission:

if( !empty( $_POST[ 'varname' ] ) )
{
    // Logic
    $loginquery = mysqli_query($connection,"SELECT * FROM users WHERE username = '$username' AND password = '$password'");
    $user = mysqli_fetch_array($loginquery);
    session_start();
    $_SESSION['username'] = $user['username'];
    echo $_SESSION['username'];
}

OR:

if( !empty( $_GET[ 'varname' ] ) )
{
    // Logic
    $loginquery = mysqli_query($connection,"SELECT * FROM users WHERE username = '$username' AND password = '$password'");
    $user = mysqli_fetch_array($loginquery);
    session_start();
    $_SESSION['username'] = $user['username'];
    echo $_SESSION['username'];
}
Vladimir Ramik
  • 1,920
  • 2
  • 13
  • 23