creating a log in page using php and PDO however once I fill out the form with the correct username and password to log into the system and click log in, nothing changes except the boxes are now empty as if I never entered a username and password, can someone advise me as to what is going wrong?
this is the php code:
<?php
session_start();
$server = "127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$db = "movie1";
$message = "";
try
{
$handle = new PDO("mysql:host=$server; dbname=$db", $dbusername, $dbpassword);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
}
else
{
$query = "SELECT * FROM register WHERE username = :username AND password = :password";
$statement = $handle->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:login_success.php");
}
else
{
$message = 'Wrong Data';
}
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
?>
and this is the html form to which it applies to:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>log in</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<form class="w3-container w3-card-4" action="login.php" method="post">
<h2 class="w3-text-black">Log in</h2>
<?php
if(isset($message))
{
echo '<label class "text-danger">'.$message.'</label>';
}
?>
<p>
<label class="w3-text-black"><b>username</b></label>
<input class="w3-input w3-border" name="username" type="text" placeholder="username"></p>
<p>
<label class="w3-text-black"><b>Password</b></label>
<input class="w3-input w3-border" name="password" type="text" placeholder="********"></p>
<p>
<input type="submit" name="login" class="w3-btn w3-black">Log in</input>
</p>
<p>
please ignore that passwords are not hashed, I will fix that later. the first image is what the log in form looks like with information entered and the next will be what happens after I click log in (pic one)1
pic two 2
I have made only minor changes to get your script working, see comments below. I think your login_success.php sends the authenticated user back to the login page.
<?php
/* my table in db named 'movie1':
CREATE TABLE `register` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL
);
INSERT INTO `register` (`username`, `password`) VALUES
('User1', '1111'),
('User2', '2222');
*/
session_start();
$server = "127.0.0.1";
$dbusername = "www"; //Changed
$dbpassword = "www"; //Changed
$db = "movie1";
$message = "";
try
{
$handle = new PDO("mysql:host=$server; dbname=$db", $dbusername, $dbpassword);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
$message = '<label>All fields are required</label>';
else
{
$query = "SELECT * FROM register WHERE username = :username AND password = :password";
$statement = $handle->prepare($query);
$statement->execute(
array(
':username' => $_POST["username"], //Inserted colon here
':password' => $_POST["password"] //Inserted colon here
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:FileNotExistAndWillProduce404WhichMeansSuccess.php");//Target changed
}
else
$message = 'Wrong Data';
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>log in</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<form class="w3-container w3-card-4" action="LoginTest.php" method="post"> <!-- action-target changed -->
<h2 class="w3-text-black">Log in</h2>
<?php
if($message>'') //was isset(), changed, because it contains at least an empty string
echo '<label class "text-danger">'.$message.'</label>';
?>
<p>
<label class="w3-text-black"><b>username</b></label>
<input class="w3-input w3-border" name="username" type="text" placeholder="username"></p>
<p>
<label class="w3-text-black"><b>Password</b></label>
<input class="w3-input w3-border" name="password" type="text" placeholder="********"></p>
<p>
<input type="submit" name="login" class="w3-btn w3-black">Log in</input>
</p>
</form></body></html>
Related
Is this code okay? as I do not receive any errors at all.
session.php
<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to welcome page
if (isset($_SESSION["userid"]) && $_SESSION["userid"] === true) {
header("location: welcome.php");
exit;
}
?>
login.php
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// validate if email is empty
if(empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
// validate if password is empty
if(empty($password)) {
$error .= '<p class="error">Please enter your password.</p>';
}
if(empty($error)) {
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s', $email);
$query->execute();
$row = $query->fetch();
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$_SESSION["user"] = $row;
// Redirect the user to welcome page
header("location: welcome.php");
exit;
} else {
$error .= '<p class="error">The password is not valid.';
}
} else {
$error .= '<p class="error">No User exist with that email address.';
}
}
$query->close();
}
// Close connection
mysqli_close($db);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Login</h2>
<p>Please fill in your email and password.</p>
<form action="" method="post">
<div class="form-group">
<label>Email Address</label>
<input type="email" name="email" class="form-control" required />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<p>Don't have an account? Register here.</p>
</form>
</div>
</div>
</div>
</body>
</html>
welcome.php
<?php
// start the session
session_start();
// Check if the user is not logged in, then redirect the user to login page
if (!isset($_SESSION["userid"]) || $_SESSION["userid"] !== true) {
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome <?php echo $_SESSION["name"]; ?></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Hello, <strong><?php echo $_SESSION["name"]; ?></strong>. Welcome to demo site.</h1>
</div>
<p>
Log Out
</p>
</div>
</div>
</body>
</html>
welcome.php changed to -
<?php
// start the session
session_start();
// Check if the user is not logged in, then redirect the user to login page
if (empty($_SESSION['user'])) {
header("location: login.php");
exit;
}
?>
session.php changed to =
<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to welcome page
if (empty($_SESSION['user']) === false) {
header("location: welcome.php");
exit;
}
?>
register.php -
<?php
require_once "config.php";
require_once "session.php";
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['submit'])) {
$fullname = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$error = '';
$query->bind_param('s', $email);
$query->execute();
$query->store_result();
if ($query->num_rows > 0) {
$error .= '<p class="error">The email address is already registered!</p>';
} else {
if (strlen($password ) < 6) {
$error .= '<p class="error>Password must have atleast 6 characters.</p>';
}
// Validate confirm password
if (empty($confirm_password)) {
$error .= '<p class="error">Please enter confirm password.</p>';
} else {
if (empty($error) && ($password != $confirm_password)) {
$error .= '<p class="error">Password did not match.</p>';
}
}
if (empty($error) ) {
$insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
$insertQuery->bind_param("sss", $fullname, $email, $password_hash);
$result = $insertQuery->execute();
if ($result) {
$error .= '<p class="success">Your registration was successful!</p>';
} else {
$error .= '<p class="error">Something went wrong!</p>';
}
}
}
}
$query->close();
$insertQuery->close();
// Close DB connection
mysqli_close($db);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Register</h2>
<p>Please fill this form to create an account.</p>
<form action="" method="POST">
<div class="form-group">
<label>Full Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group">
<label>Email Address</label>
<input type="email" name="email" class="form-control" required />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<p>Already have an account? Login Here.</p>
</form>
</div>
</div>
</div>
</body>
</html>
logout.php -
<?php
// Start the session
session_start();
// Destroy the session.
if (session_destroy()) {
// redirect to the login page
header("Location: login.php");
exit;
}
?>
config.php
<?php
define('DBSERVER', 'localhost'); // Database server
define('DBUSERNAME', 'root'); // Database username
define('DBPASSWORD', ''); // Database password
define('DBNAME', 'demo'); // Database name
/* connect to MySQL database */
$db = mysqli_connect(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
// check db connection
if($db === false){
die("Error: connection error. " . mysqli_connect_error());
}
?>
db.sql - that connects to the server verifed it adds to the database using phpmyadmin so the registration is working.
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(75) NOT NULL,
`password` varchar(7255) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
EDIT: added the changes to the session.php + welcome.php + added the whole files of the whole code.
I am trying to set up a login system but the page is not doing the validation of the user and passwors. I know is connecting to the database but it doesn't show any results after the for each statement.
I have two files one for the login form(login.php) and one for the login to the database(process.php).
Here is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Login Page</title>
</head>
<body>
<div>
<form action="process.php" method="POST">
<p>
<label>Username:</label>
<input type="text" id="user" name="user">
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass">
</p>
<p>
<label>Username:</label>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php
<?php
//Get values from login.php file
$username = $_POST['user'];
$password = $_POST['pass'];
//Stop SQL injection
/* $username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);*/
//Connect to the server and select database
$domainsn = 'mysql:host=localhost;dbname=login';
$username = 'root';
$password = 'costarica';
try {
$db = new PDO ($domainsn, $username, $password);
echo "Connected";
} catch (Exception $e) {
$error_message = $e->getMessage();
echo "Coudn't connect due to $error_message";
}
$query = "SELECT * FROM users WHERE username = '$username' AND password ='$password'";
$result = $db->query($query);
//echo "$result";
foreach ($result as $results) {
echo "$results";
echo $users['id'];
if ($results['username'] == $username && $results['password'] == $password) {
echo "Login success!!! Welcome ".$results['username'];
} else {
echo "failed try {} catch ( $e) {}";
}
}
?>`enter code here`
You can use this i hope it will help.
$query = "SELECT * FROM users WHERE username = '".$username."' AND password ='".$password."' ";
$result = $db->query($query);
if($result->num_rows>0){
// User exists
}else{
// User not exists.
}
I want to create a working login form. Here's what I have done and this displays cannot select db.
Edited login.php file
<?php
error_reporting(E_ALL);
//Connection Variables:
$dbhost = "localhost";
$dbname = "";
$dbuser = "";
$dbpass = "";
try{
//Connection to SQL:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
//Error messagin enabled:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$user = '';
$pass = '';
$sum = 0;
$error_msg = "Please type a username and a password";
if(isset($_POST['login']))
{
//Start a session:
session_start();
$user = $_POST['email'];
$pass = $_POST['password'];
if(empty($user) && empty($pass))
{
echo $error_msg;
$pass = '';
}
if(empty($user) || empty($pass))
{
echo $error_msg;
$user = '';
$pass = '';
}
if(!empty($user) && !empty($pass))
{
//SQL:
$query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
$query->bindParam(":u", $user);
$query->bindParam(":p", $pass);
//Execute query:
$query->execute();
$number_rows = $query->fetch(PDO::FETCH_NUM);
if($number_rows>0)
{
echo $user;
$_SESSION['usern'] = $user;
$_SESSION['passw'] = $pass;
header("Location: ./pages/home.php");
}
//echo $user;
else
{
echo "Invalid username or password";
header("Location: index.html");
}
}
}
if(!isset($_POST['login']))
{
echo "Login button not clicked";
}
?>
I read more and more articles on this, still I can't find a solution.
Edited HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Signin for OTMS</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="signin.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form action="login.php" method="post" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Sign in</button>
</form>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
Please help me to find what is the error.
I created my database using phpMyAdmin and it's in localhost. And interfaces I designed using Bootstrap.
This is the error I'm getting now:
database name- otmsdb
table name- login
email, passowrd,
button name- login
Sir, your code is vulnerable to SQL injections. Please start using MySQLi or PDO. Here is a PDO code for login that should works fine with you:
Source: Udemy Online course.
EDIT: use this code, and change the variables into yours
<?php
session_start();
if(isset($_POST['login'])){
$errmsg_arr = array();
// configuration
$dbhost = "localhost";
$dbname = "your database name";
$dbuser = "your username";
$dbpass = "your password";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// new data
$user = $_POST['username'];
$password = $_POST['password'];
if($user == '') {
$errmsg_arr[] = 'You must enter your Username';
}
if($password == '') {
$errmsg_arr[] = 'You must enter your Password';
}
// query
if (!$errmsg_arr) {
$result = $conn->prepare("SELECT * FROM login WHERE username= :user");
$result->execute(['user' => $username]);
$row = $result->fetch(PDO::FETCH_NUM);
if($row && password_verify($_POST['password'], $row['password']) {
$_SESSION['user'] = $row;
header("location: ./pages/home.php");
exit;
}
else{
$errmsg_arr[] = 'Username and Password are not found';
}
}
}
?>
HTML FORM:
<body>
<?php foreach($errmsg_arr as $msg): ?>
<?=htmlspecialchars($msg, ENT_QUOTES) ?><br>
<?php endforeach ?>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" value="<?=htmlspecialchars($user, ENT_QUOTES)?>" />
<input type="password" name="password" placeholder="password" value="<?=htmlspecialchars($password, ENT_QUOTES)?>"/>
<input type="submit" name="login_submit" value="login"/>
</form>
</body>
Suggestions:
echo mysql_error() to determine why the error is occurring:
mysql_select_db("$db_name") or
die("cannot select DB: " . mysql_error());
Stop using deprecated functions " mysql_connect()", "mysql_query()" and friends. You'd be much better served with mysqli instead.
Use Prepared Statements instead of building your "select" directly from your POST parameters.
I am trying to make a login-register website for learning purposes and I can't make the password_verify work. The registration works perfectly. The value from the fetched array in the login.php is the same as in the database. The database connection works. Still, it always goes to Access denied when calling the password_verify function.
index.php
<!DOCTYPE html>
<html>
<!-- Head -->
<head>
<title>Small Content Management System</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href='http://fonts.googleapis.com/css?family=PT+Sans+Narrow' rel='stylesheet' type='text/css'>
</head>
<!-- End head -->
<!-- Body -->
<body>
<div id="login">
<h2>Small CMS</h2>
<form name="login" method="post" action="functions/login.php">
Username:</br>
<input type="text" name="username"></br>
Password:</br>
<input type="password" name="password"></br>
<input type="submit" name="submit" value="Login">
</form>
<span id="register">Don't have an account? Register!</span>
</div>
</body>
<!-- End Body -->
</html>
register.php
<!DOCTYPE html>
<html>
<!-- Head -->
<head>
<title>Small Content Management System</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/register.css">
<link href='http://fonts.googleapis.com/css?family=PT+Sans+Narrow' rel='stylesheet' type='text/css'>
</head>
<!-- End head -->
<!-- Body -->
<body>
<div id="login">
<h2>Small CMS</h2>
<form name="register" method="post" action="functions/register.php">
Username:</br>
<input type="text" name="username"></br>
E-mail:</br>
<input type="text" name="email"></br>
Password:</br>
<input type="password" name="password"></br>
<input type="submit" name="submit" value="Register">
</form>
<span id="register">Already have an account? Login!</span>
</div>
</body>
<!-- End Body -->
</html>
login.php
<?php
include_once '../../db.php';
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (trim($username) != '' && trim($password) != '') {
$con = new Connection();
$query = $con->db->prepare("SELECT * FROM users WHERE username=?");
$query->bindParam(1, trim($username)) ;
$query->execute();
$res = $query->fetch(PDO::FETCH_ASSOC);
if (password_verify(trim($password), trim($res['password']))) {
echo 'Access granted!';
} else {
echo 'Access denied!';
}
} else {
echo 'Username or password invalid!';
}
}
functions/register.php
<?php
include_once('../../db.php');
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
// Error message to catch
$err = '';
// Check if user, password and email are empty
if (trim($username) === '') {
$err = 'Invalid username!</br>';
}
if (trim($password) === '') {
$err .= 'Invalid password!</br>';
}
if (trim($email) === '') {
$err .= 'Invalid email!<br>';
}
// Checking if user is already in use
$con = new Connection();
$query = $con->db->prepare('SELECT * FROM users WHERE username=?');
$query->bindParam(1, $username);
$query->execute();
$results = $query->rowCount();
if ($results != 0) {
$err .= 'Username already in use!</br>';
}
// Checking if email is already in use
$con = new Connection();
$query = $con->db->prepare('SELECT * FROM users WHERE email=?');
$query->bindParam(1, $email);
$query->execute();
$results = $query->rowCount();
if ($results != 0) {
$err .= 'Email already in use!</br>';
}
// Inserting new user into database
if ($err === '') {
// Connecting to db
$con = new Connection();
$query = $con->db->prepare("INSERT INTO users(username, password, email) VALUES (?, ?, ?)");
$options = [
'cost' => 12,
];
$new_pass = password_hash($password, PASSWORD_BCRYPT, $options);
$query->bindParam(1, trim($username));
$query->bindParam(2, trim($new_pass));
$query->bindParam(3, trim($email));
$query->execute();
} else {
echo $err;
}
}
Alright, it was the column length, thank you for your help! – Trooper
Comment to answer.
Looking at your posted code, everything seems to check out.
The likelyhood in my view at the time being:
The column length should be long enough to accomodate the hash. If it's too short and is stored as such, then retrieval will be impossible. Many use too low a number for their varchar. Use 255 which will also accomodate for the future.
If that is the case, you need to start over with a new register/insert.
Which in the end, was the case; too short a length for the column.
The database is set up correctly but I the error handler when I dont enter a username or password is not working. I always get Invalid username and/or password
The following code doesn't go the the "loginhandler.php" link
Any ideas to why?
No matter the input the code executes`
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<?php
$okay = FALSE;
$username = ($_POST['username']);
$password = ($_POST['password']);
$onError = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['username'])) {
$onError = 'Please Enter your Username';
$okay = FALSE;
}
if (empty($_POST['password'])) {
$onError = 'Please Enter your password';
$okay = FALSE;
}
if($okay == FALSE)
{
$dbc = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('db_name', $dbc);
$query = "SELECT * FROM signup WHERE username = '" . $username . "' AND password='" . $password . "'";
if ($result = mysql_query($query, $dbc)) {// Run the query.
while ($row = mysql_fetch_array($result)) {
$okay = true;
}
} else {
}
}
if ($okay) {
// session_start();
$_SESSION['username'] = $username;
header('Loction: loginhandler.php');
exit() ;
} else {
$onError = "Invalid username and/or password";
}
}
?>
<!-- Begin Page Content -->
<div id="container">
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<div class="error"><?php echo $onError; ?></div>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
<p>Click here to Signup.</p>;
</div><!--/ lower-->
</form>
</div><!--/ container-->
<!-- End Page Content -->
</body>
</html>`
$onError = "Invalid username and/or password";
First, you are using session. add session_start() at the top of the page.
header('Location: loginhandler.php'); you wrote Location wrong.
if($okay == FALSE) Should be if($okay == TRUE)
And you alweyes getting the invalid message because you have "$onError = "Invalid username and/or password";" at the bottom of the code outside any PHP tags.