I have attempted to create a simple form with register and login/logout page. But it keeps giving me errors. Please help.
Notice: Undefined index: username in ..path/to/index.php on line 4
Notice: Undefined index: password in ..path/to/index.php on line 5
Warning: Cannot modify header information - headers already sent by (output started at ..path/toindex.php:4) in ..path/to/index.php on line 8
Login.php
session_start();
$username = $_SESSION['username'];
$password = $_SESSION['password'];
if($username && $password)
{
header( 'Location: index.php' );
}
else
{
function index()
{
echo "<form action='' method='post'>"
."Username:<input type='text' name='username' size='30'>"
."Password:<input type='password' name='password' size='20'>"
."<input type='submit' value='Login' name='login'/>"
."</form>";
}
function login()
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if ($username=="")
{
die("<br /> You Forgot to type in your Username!");
}
if ($password=="")
{
die("<br /> You Forgot to type in your Password!");
}
$con=mysqli_connect("localhost" ,"root" , "root" ,"user");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query("SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
$user = $row['username'];
if($username != $user)
{
die("<br />Username is wrong!<br /> ");
}
$real_password = $row['password'];
if($password != $real_password)
{
die("<br />Your password is wrong!<br /> ");
}
$_SESSION['username']=$username;
$_SESSION['password']=$password;
header( 'Location: index.php' ) ;
}
if (isset($_REQUEST['login']))
{
login();
}
else
{
index();
}
}
?>
logout.php
<?php
session_start();
session_destroy();
header( 'Location: login.php' ) ;
?>
Register.php
<?php
session_start();
echo "<h2 style='padding-left: 10px'>Register A User :</h2>"
."<form action='' method='post'>"
."Username :<input type='text' name='user' size='30'>"
."Password :<input type='password' name='password' size='20'>"
."<input type='submit' value='Register' name='register' />";
if (isset($_REQUEST['register']))
{
$username = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
if ($username=="")
{
die("<br /> You Forgot to type in the Username for the user ! <br /> ");
}
if ($pass=="")
{
die("<br />You Forgot to type in the Password for the user !<br />");
}
$con=mysqli_connect("localhost" ,"root" , "root" ,"user");
// check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query("INSERT INTO users (username, password) VALUES ('$username', '$pass') ");
}
?>
index.php
<?php
session_start();
$username = $_SESSION['username'];
$password = $_SESSION['password'];
if(!$username && !$password)
{
header( 'Location: login.php' ) ;
}
else
{
echo "<h3>Welcome to My Webpage</h3>";
}
?>