Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
im trying to create a simple login and register page
and i am getting these errors on my index .php
page,why is my index undefined these are the errors i am getting
Notice: Undefined index: username in C:\xampp\htdocs\mysite\forum part two\index.php on line 7
Notice: Undefined index: password in C:\xampp\htdocs\mysite\forum part two\index.php on line 8
the codes on line 7 and 8 these respectively
$username = $_SESSION['username'];
$password = $_SESSION['password'];
this is my index page
<?php
//This will start a session
session_start();
$username = $_SESSION['username'];
$password = $_SESSION['password'];
//Check do we have username and password
if(!$username && !$password){
echo "Welcome Guest! <br> <a href=login.php>Login</a> | <a href=register.php>Register</a>";
}else{
echo "Welcome ".$username." (<a href=logout.php>Logout</a>)";
}
?>
You are getting those errors because your session has not been declared earlier,So you need to check if your session is declared earlier. you can use php empty or isset function
<?php
//This will start a session
session_start();
$username ='';$password ='';
if(!empty($_SESSION['username']))//check if it is defined
$username = $_SESSION['username'];
if(!empty($_SESSION['password']))//check if it is defined
$password = $_SESSION['password'];
//Check do we have username and password
if($username=='' && $password==''){
echo "Welcome Guest! <br> <a href=login.php>Login</a> | <a href=register.php>Register</a>";
}else{
echo "Welcome ".$username." (<a href=logout.php>Logout</a>)";
}
?>
Check to see if the $_SESSION's
store any values..
I'll give you an example:
<?php
//This will start a session
session_start();
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}else{
$username = null;
}
var_dump($username);
// Would return NULL. SESSION IS NOT SET.
// if I add $_SESSION['username'] = "Phorce" session set, will return phorce.
?>
Or: var_dump($_SESSION['username']);
Hope this helps :) It could be that $_SESSION['username']
isn't registering.
Please check that there is value assigned to session variable before using it.
<?php
//This will start a session
session_start();
$username ="";
$password ="";
if(isset($_SESSION['username']))
$username = $_SESSION['username'];
if(isset($_SESSION['password ']))
$password = $_SESSION['password'];
//Check do we have username and password
if(!$username && !$password){
echo "Welcome Guest! <br> <a href=login.php>Login</a> | <a href=register.php>Register</a>";
}else{
echo "Welcome ".$username." (<a href=logout.php>Logout</a>)";
}
?>