A couple things to note here, javascript is not needed and processing of data was poorly written, but thats a given since I believe you are new to PHP.
Anyway, I re-wrote it and commented it, you may need to slightly adjust, but the majority is there and should work without error.
PHP Code:
<?php
session_start();
// Check if form is posted
// Check username and password is set and neither fields are empty - buh bye JS thats not needed!
if(isset($_POST['username']) AND !empty($_POST['username']) AND isset($_POST['password']) AND !empty($_POST['password']))
{
// Its posted if its here, so secure the data before its put into a database string - I suggest learning security and doing better than simply MRES
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
// Check the database for both username and password relation to given details.
$logincheck = mysql_query("SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password' LIMIT 1") or die (mysql_error());
// If the record doesnt exist, error and tell them.
if(!mysql_num_rows($logincheck)
{
// Include the header here, so no html is output previously, so if the details are correct, you can redirect with header()
include_once('includes/header.php');
echo '<strong>';
echo 'Login Failed, either your username or your password is incorrect!';
echo '<br /><br />';
echo 'If you forgot your password click <a href="forgotpass.php">here</a>';
echo '</strong>';
}
else
{
// Given details match a user in the database, so set the query into a variable.
$login = mysql_fetch_assoc($logincheck);
// Set sessions...
$_SESSION['username'] = $login['username'];
// This is crazy to have a session simply containing a raw password string, add it to md5 and add a salt, for simplicity, I will use password with a salt of the username.
$_SESSION['password'] = md5($login['password'] . $login['username']);
echo $_SESSION['username'];
header('Location: usercp.php');
}
}
else // Else if form is not submitted... - PHP does the checking when you submit, JS not needed!
{
// Include header - again, cant be at the top because if the user gives correct username and password, it redirects - Wont work with header() if there is any output previously on the page.
include_once('includes/header.php');
// The form.
echo '<form name="login" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
echo 'Username: <input type="text" name="username" value="'; if(isset($_POST['username'])) { echo $_POST['username']; } echo '" />';
echo '<br />';
echo 'Password:<input type="password" name="password" value="'; if(isset($_POST['password'])) { echo $_POST['password']; } echo '" />';
echo '<br />';
echo '<input type="submit" name="submit" value="Log In">';
echo '</form>';
}
include('includes/footer.php');
?>
Also, every page where you want it to keep hold of the sessions, needs session_start(); at the top of the file.
PHP Code:
<?php
session_start();