Hate to say this, but your code was a mess. I'm going to tell you what I fixed now.
Errors:
You were missing a ?> at the end of your file
(?) Check to see if MySQL is on and if you have a database.
Some places in the code didn't have quotes, but they are strings.
Warnings:
I would use cookies instead of sessions (Fixed)
Please style your code. (Fixed)
Please make sure that you md5 the password of every user so that it's not in a readable format. (ex. md5($password))
Make sure your HTML syntax is correct (Fixed by adding </body> and </html>)
PHP Code:
<html>
<head>
<title>Login Page</title>
</head>
<body bgcolor="black" style="color:gray">
<form action="#" method="post">
<h1 align="center" style="color:gray" >Welcome to the Login page</h1>
<?php
error_reporting(0);
$servername = "localhost"; //MySQL server
$username = "root"; //MySQL username
$password = ""; //MySQL password (Leave blank if no password)
$conn = mysql_connect($servername,$username,$password)or die(mysql_error());
if($_POST["userlogin"] && $_POST["password"]) { //If the user has submitted the user login form
mysql_select_db("dbUsers",$conn);
$sql = "SELECT * FROM users WHERE name = '" . $_POST["userlogin"] . "' AND password = '" . $_POST["password"] . "'";
$result = mysql_query($sql,$conn) or die(mysql_error());
$number_of_rows = mysql_num_rows($result);
if($number_of_rows == 1) {
setcookie("username", $_POST["userlogin"], time()+ 3600); //Automatically expires cookie in one hour, 3600 seconds
setcookie("password", $_POST["password"], time()+ 3600);
print"<h1>You have logged in.</h1>";
//print_secure_content();
}
else {
print "Wrong username or password.";
loginform();
}
}
else if($_COOKIE["username"] && $_COOKIE["password"]) {
//User is logged in, but he's on the login page. Print the secure content after verifying the login again!
mysql_select_db("dbUsers",$conn);
$sql="SELECT * FROM users WHERE name = '" . $_COOKIE["username"] . "' AND password = '" . $_COOKIE["password"] . "'";
$result=mysql_query($sql,$conn) or die(mysql_error());
$number_of_rows = mysql_num_rows($result);
if($number_of_rows == 1) {
//Print the secure login information
//print_secure_content();
}
else {
//The user somehow has a bad cookie! Bring him to the login form.
loginform();
}
}
else {
//User is not logged in, therefore display the login form.
loginform();
}
function loginform() {
print "Please enter your username and password.";
print ("<table border='2'><tr><td>username</td><td><input type='text' name='userlogin' size'20'></td></tr><tr><td>password</td><td><input type='password' name='password' size'20'></td></tr></table>");
print "<input type='submit' >";
print "<h3><a href='registerform.php'>register now!</a></h3>";
}
?>
</form>
</body>
</html>
Side Note:
Make sure you have a MySQL DB called dbUsers with table users
45eOF.png