I've been trying to create a login form for my website but the form seems unable to connect to the table or retrieve info from it. I even tried obtaining some sample code online, but it is still not being able to connect. Here's the code:
session_start();
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is empty";
} else {
$username=$_POST['username'];
$password=$_POST['password'];
$connection = mysqli_connect("localhost", "user", "pass");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$db = mysqli_select_db($connection, "cpses_company");
$query = mysqli_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection);
}
}
No matter what values I insert, I keep getting the error code "Username or Password is invalid". The table does contain values and I get this error even when I am inserting the values correctly. I am assuming that it is unable to connect to the database or the table. Any ideas?
edit: HTML (index.php)
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user']))
{
header("location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
The problem exist here:-
$query = mysqli_query("select * from login where password='$password' AND username='$username'", $connection);
You need make $connection as first parameter like this:-
$query = mysqli_query($connection,"select * from login where password='$password' AND username='$username'");
Note:- try always to use mysql error reporting so that you will get rid of the problem like you are facing. for that you need to do like below very simple:-
$query = mysqli_query($connection,"select * from login where password='$password' AND username='$username'")or die(mysqli_error($connection));
Some other issue are there, so for your help, Please try like this:-
<?php
session_start();
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is empty";
} else {
//$username=$_POST['username'];
//$password=$_POST['password'];
$connection = mysqli_connect("localhost", "user", "pass","cpses_company"); // direct give db name here
// remove that two line what i said in comment also
$username = mysqli_real_escape_string($connection,$_POST['username']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$query = mysqli_query($connection,"select * from login where password='$password' AND username='$username'") or die(mysqli_error($connection));
//$rows = mysqli_num_rows($query);//comment this line
if ($query->num_rows > 0) {
$_SESSION['login_user']=$username;
header("location: profile.php");
exit;
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection);
}
}
?>
As mysqli_query need paramater like this:-
mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
Read mysqli_query
So your mysqli_query would be:-
First parameter connection then query
$query = mysqli_query($connection,"select * from login where password='$password' AND username='$username'");
UPDATED
<?php
session_start();
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is empty";
} else {
$username=$_POST['username'];
$password=$_POST['password'];
$connection = mysqli_connect("localhost", "user", "pass","cpses_company"); // direct give db name here
// remove that two line what i said in comment also
$username = mysqli_real_escape_string($connection,$username);
$password = mysqli_real_escape_string($connection,$password);
$query = mysqli_query($connection,"select * from login where password='$password' AND username='$username'") or die(mysqli_error($connection));
//$rows = mysqli_num_rows($query);//comment this line
if ($query->num_rows > 0) {
$_SESSION['login_user']=$username;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection);
}
}
?>
Related
I am new to php, I'm trying to link the login page and register page. Once I press the login button it goes directly to the linked page although I enter wrong password.
I tried to solve it by putting mysqlinumrows. The result after login is still in the login page . I've tried to fix it, but can't. I hope someone will help me to reduce my stress by knowing my fault in the code below I attach.
Code:
<?php
session_start();
$_SESSION['message'] = '';
$mysqli=new MySQLi('127.0.0.1','root','','accounts');
if($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['password']== $_POST['confirmpassword']) {
$username = $mysqli->real_escape_string($_POST['username']);
$email = $mysqli->real_escape_string($_POST['email']);
$password = md5($_POST['password']);
$profile_path = $mysqli->real_escape_string('images/'.$_FILES['profile']['name']);
if (preg_match("!image!", $_FILES['profile']['type'])) {
if (copy($_FILES['profile']['tmp_name'],$profile_path)){
$_SESSION['username'] =$username;
$_SESSION['profile'] =$profile_path;
$sql ="INSERT INTO users(username,email,password,profile)"
."VALUES ('$username','$email','$password','$profile_path')";
if($mysqli->query($sql)=== true) {
$_SESSION['message'] = 'Registration successful!
Added $username to the database!';
header("location:RegisterLogin.php");
}
else {
$_SESSION['message'] = "User could not be added to the database!";
}
}
else{
$_SESSION['message'] = "file failed!";
}
}
else {
$_SESSION['message'] = "Please only upload GIF,JPG, or PNG images!";
}
}
else{
$_SESSION['message'] = "two password do not match!";
}
}
?>
(Login Form)
<?php
session_start();
$_SESSION['message']='';
$mysqli=new MySQLi('127.0.0.1','root','','accounts');
if(isset($_POST['username'])) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$sql="SELECT * FROM users WHERE username ='$username' AND password=$password";
$result = mysqli_query($mysqli,$sql);
if(mysqli_affected_rows($result) == 1){
$_SESSION['username'] = $username;
$_SESSION['message'] = "Registration successful!";
header("location:Welcome.php");
}
else{
$_SESSION['message'] = "Login Failed!";
}
}
?>
Correct your select query in login page to $sql="SELECT * FROM users WHERE username ='$username' AND password='$password' "; Add single quotes to password variable
First you must have form tag. try this format
<form action="" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login">
</form>
And for your PHP code:
if(isset($_POST['login'])) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$sql="SELECT * FROM users WHERE username ='$username' AND password=$password";
$result = mysqli_query($mysqli,$sql);
if(mysqli_affected_rows($result) == 1){
$_SESSION['username'] = $username;
$_SESSION['message'] = "Registration successful!";
header("location:Welcome.php");
}
else{
$_SESSION['message'] = "Login Failed!";
}
}
If It's not your problem then comment it below. I'll help you.
I'm having a very annoying problem with a very simple PHP login script. The problem is that the login works even with wrong username and/or password. I'm running it in XAMPP 7.0.8 for Linux. By the way, the table "users" of the database "login" has only one row.
I've been trying to understand how these kind of scripts work, so I tried with the most basic kind of login I could. But it keeps being a mystery to me, by now I've never could make it work it out.
Here is the PHP part:
<?php
session_start();
if(isset($_POST['login'])) {
$db = mysqli_connect("localhost", "root", "", "login");
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM users WHERE username = '$username' LIMIT 1";
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query);
$id = $row['id'];
$db_password = $row['password'];
if($password == $db_password){
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: index.php");
} else {
echo "Error: the information is not correct.";
}
}
?>
And here the HTML form:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Client's area</title>
</head>
<body>
<form method="post" action="">
<input type="text" name="username">
<input type="password" name="password">
<input class="login" type="submit" name="login" value="Login">
</form>
</body>
</html>
Edit: the idea of this post was never trying to make a secure login script, it was intended to understand some PHP features. I recognize it's not safe to use any part of this code for an actual login project.
You can use a simple query
$sql = "SELECT * FROM users WHERE username = '$username' and password= '$password'";
$query = mysqli_query($db, $sql);
if(mysqli_num_rows($query) > 0)
{
//Records matched process further
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: index.php");
exit();
} else {
//Record not found throw error
echo "Error: the information is not correct.";
}
Hope this helps
The problem is you are setting the $row variable directly even if it fails. This sets the $db_password to '' and the password should be ''. Hence it passes.
change the $row command to this
if ($row = mysqli_fetc_array($query) {
and add a } to the 3rd line from the bottom (the blank spot) and add your 'failure message' there as well
I got 3 files which is connection.php, work.php, and login.php
I am currently working with log-in.
The name of my database is wildlife and it has a field of
wrd_username(for username) AND wrd_password(for password)
I am having a difficulty because the SQL is unable to detect the username and password.
MySQL is required for this PHP.
Please kindly help me.
connection.php
<?php
$conn = mysql_connect('localhost', 'root', '', 'wildlife');
if (!$conn)
{
die('Connect Error: ' . mysql_errno());
}
else
{
echo ("connected from connection.php");
}?>
work.php
<?php
include('login.php');
?>
<html>
<head><title>howww</title>
</head>
<body>
<form action="login.php" method="post"> <!-- Sign In Process -->
Username: <input type="text" name="user" id="emp_username"style="width:150">
<br />
Password: <input type="password" name="pass" id="emp_password"style="width:153">
<br />
<br />
<input type="submit" value="submit">
</form>
</body>
</html>
login.php
enter code here
<?php
// Try and connect to the database
include('connection.php');
$selected = mysql_select_db("wildlife",$conn)
or die("Could not select ");
//$myusername = mysql_real_escape_string($conn,$_POST['username']);
//$mypassword = mysql_real_escape_string($conn,$_POST['password']);
if(isset($_POST['user']) && isset($_POST['pass'])){
$emp_username = $_POST['emp_username'];
$emp_password = $_POST['emp_username'];
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$user' and emp_password='$pass'");
if(mysql_num_rows($query) > 0 )
{
//check if there is already an entry for that username
echo "DETECTED Username AND PASS already exists!";
}
else
{
//header("location:index.php");
echo(" okay");
//header('work.php');
}
}
mysql_close();
?>
whenever I try to input the username and password it always ended up with okay from login.php
Your error seems to be assigning the wrong $_POST variable to password variable:
$emp_password = $_POST['emp_username'];
It should be something lke:
$emp_password = $_POST['emp_password'];
Also, your code is vulnerable to SQL injections. Try learning to use prepared statements.
You need to do these changes into your login.php file
<?php
// Try and connect to the database
include('connection.php');
$selected = mysql_select_db("wildlife",$conn)
or die("Could not select ");
//$myusername = mysql_real_escape_string($conn,$_POST['username']);
//$mypassword = mysql_real_escape_string($conn,$_POST['password']);
if(isset($_POST['user']) && isset($_POST['pass'])){
$emp_username = $_POST['user']; //name as of html form
$emp_password = $_POST['pass']; //name as of html form
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$user' and emp_password='$pass'");
if(mysql_num_rows($query) > 0 )
{
//check if there is already an entry for that username
echo "DETECTED Username AND PASS already exists!";
}
else
{
//header("location:index.php");
echo(" okay");
//header('work.php');
}
}
mysql_close();
?>
Your $user and $pass variable are empty always.I have update the login.php page below. Use the below code
<?php
// Try and connect to the database
include('connection.php');
$selected = mysql_select_db("wildlife",$conn)
or die("Could not select ");
//$myusername = mysql_real_escape_string($conn,$_POST['username']);
//$mypassword = mysql_real_escape_string($conn,$_POST['password']);
if(isset($_POST['user']) && isset($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$user' and emp_password='$pass'");
if(mysql_num_rows($query) > 0 )
{
//check if there is already an entry for that username
echo "DETECTED Username AND PASS already exists!";
}
else
{
//header("location:index.php");
echo(" okay");
//header('work.php');
}
}
mysql_close();
?>
I believe the problem is:
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$user' and emp_password='$pass'");
Should be:
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$emp_username' and emp_password='$emp_password'");
Looks like you just had some unused variables in your query to MySQL ($user and $pass weren't really assigned to anything). Other than that, everything looks good.
In just 3 lines, it should like this :
$user = $_POST['emp_username'];
$pass = $_POST['emp_password'];
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$user' and emp_password='$pass'");
In connection.php page no need to add database with mysql_connect('localhost', 'root', '','wildlife') as you use it in login.php page mysql_select_db("wildlife",$conn) and in your query just add proper variable in where condition emp_username='$emp_username' and emp_password='$emp_password'"
connection.php
<?php
$conn = mysql_connect('localhost', 'root', '');
if (!$conn)
{
die('Connect Error: ' . mysql_errno());
}
else
{
echo ("connected from connection.php");
}?>
work.php
<?php include('login.php'); ?>
<html>
<head><title>PLEASE GUMANA KA NA</title>
</head>
<body>
<form action="login.php" method="post"> <!-- Sign In Process -->
Username: <input type="text" name="user" id="emp_username"style="width:150">
<br />
Password: <input type="password" name="pass" id="emp_password"style="width:153">
<br />
<br />
<input type="submit" value="submit">
</form>
</body>
</html>
login.php
enter code here
<?php
// Try and connect to the database
include('connection.php');
$selected = mysql_select_db("wildlife",$conn)
or die("Could not select ");
if(isset($_POST['user']) && isset($_POST['pass'])){
$emp_username = $_POST['user'];
$emp_password = $_POST['pass'];
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$emp_username' and emp_password='$emp_password'");
if(mysql_num_rows($query) > 0 )
{
//check if there is already an entry for that username
echo "DETECTED Username AND PASS already exists!";
}
else
{
//header("location:index.php");
echo(" okay");
//header('work.php');
}
}
mysql_close();
?>
$emp_username = $_POST['emp_username'];
$emp_password = $_POST['emp_username'];
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$user' and emp_password='$pass'");
This snippet should change to:
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysql_query("SELECT * FROM wrd_users WHERE emp_username='$user' and emp_password='$pass'");
Because the form has user and pass parameter, not emp_username or emp_password
im currently struggling to get my PHP log in to work. Iv used a separations of concerns to structure my php.
Iv already set up in my database a Users table with id, username and password values.
I dont think that there is a problem connecting to my database as i've used the same code in other projects and it works there.
This is my user_repository.php:
<?php
require_once "database.php";
function authenticate_user($username, $password, &$error) {
$sql = "select * from Users where username= '${username}'";
$sql .=" and password='{password}'";
$result = query($sql);
if ($result->num_rows!=1) {
$error = "Username or password was incroeect.";
return null;
}
return $result-> fetch_assoc();
}
function get_user_by_id($id, &$error) {
$sql = "select * from Users where id={$id} limit 1;";
$result = query($sql);
return $result->fetch_assoc();
}
?>
This is my database.php:
<?php
define("SQLHOST", "localhost");
define("SQLUSER", "b3006796");
define("SQLDB", "b3006796_db3");
define("SQLPASSWORD", "*******");
function connect_to_database () {
$mysqli = new mysqli(SQLHOST, SQLUSER, SQLPASSWORD, SQLDB);
if($mysqli->connect_errno) {
echo "failed to connect to mysql: ".$mysqli->connect_errno;
exit();
}
return $mysqli;
}
function query ($sql) {
$mysqli = connect_to_database();
$result = $mysqli->query($sql);
if (!$result) {
echo "failed to run query: ".$mysqli->error;
exit();
}
return $result;
}
?>
This is my index.php:
<?php
session_start();
require_once "user_repository.php";
$error = null;
if (isset ($_POST["username"]) && isset($_POST["password"])) {
$username = $_POST ["username"];
$password = $_POST ["password"];
// Get the assoc array for the user.
$user = authenticate_user($username, $password, $error);
//No error means valid password here.
if (!$error) {
$_SESSION['currentUser'] = $user['id'];
header("location:account.php");
exit();
}
}
?>
<html>
<head>
<title> DIWA Login </title>
</head>
<body>
<h1>login</h1>
<form method="post">
Username:<input name="username"/>
Password:<input name="password" type="password"/>
<input type="submit"/>
<?php if ($error);?>
<p><?php echo $error; ?></p>
</form?
</body>
</html>
And this is my Account.php:
<?php
session_start();
require_once "user_repository.php";
$error = null;
if (!isset($_SESSION["currentUser"])) {
header ("Location: login.php");
exit();
}
$user = get_user_by_id($_SESSION["currentUser"], $error);
?>
<html>
<head>
<title> DIWA Account </title>
</head>
<body>
<h1> Account </h1>
<p> User ID: <?php echo $user["id"]; ?></p>
</body>
</html>
Thanks
If your problem is that you cannot log in, then there is at least one bug:
`$sql .=" and password='{password}'";`
you omitted "$" at 'password', it should be
$sql .=" and password='{$password}'";
Also:
$sql = "select * from Users where username= '${username}'";
should be:
$sql = "select * from Users where username= '{$username}'";
Im trying to allow users that are on the database to log in if their credentials are present, problem is, whenever I enter details into the login screen, it will always return Invalid Login Credentials, regardless of whether or not the name/password is on the database.
Here is what I'm working with:
loginSubmit.php
<?php
//begin our session
session_start();
//Check the username and password have been submitted
if(!isset( $_POST['Username'], $_POST['Password']))
{
$message = 'Please enter a valid username and password';
}
else
{
//Enter the valid data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = sha1($password);
//Connect to the database
$SQLusername = "root";
$SQLpassword = "";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$query = "SELECT * FROM
customers WHERE name =
('$_POST[Username]' AND password = '$_POST[Password]')";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['username'] = $username;
}
else
{
echo "Invalid Login Credentials";
}
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
echo "Hello " . $username;
}
}
catch(Exception $e)
{
$message = 'We are unable to process your request. Please try again later"';
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
</body>
</html>
Login.php
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Here</h2>
<form action="loginSubmit.php" method="post">
<fieldset>
<p> <label for="Username">Username</label>
<input type="text" id="Username" name="Username" value="" maxlength="20" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" id="Password" name="Password" value="" maxlength="20" />
</p>
<p>
<input type="submit" value="Login" />
</p>
</fieldset>
</form>
</body>
</html>
AddUser
//Enter the valid data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = sha1($password);
//Connect to the database
$SQLusername = "root";
$SQLpassword = "";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$sql = "INSERT INTO
customers (name, password)
VALUES
('$_POST[Username]','$_POST[Password]')";
if(!mysql_query($sql, $dbhandle))
{
die('Error: ' . mysql_error());
}
//Unset the form token session variable
unset( $_SESSION['formToken'] );
echo "1 record added";
//close the connection
mysql_close($dbhandle);
}
catch (Exception $ex)
{
if($ex->getCode() == 23000)
{
$message = 'Username already exists';
}
else
{
$message = 'We are unable to process your request. Please try again later"';
}
It might be because of this, the way you have the brackets.
-Please see my notes about using prepared statements and password_hash() below.
SELECT * FROM customers
WHERE name = ('$_POST[Username]'
AND password = '$_POST[Password]')
Change it to:
SELECT * FROM customers
WHERE name = '$username'
AND password = '$password'
and for testing purposes, try removing
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
that could be affecting / rejecting characters. Make sure there is no white space also.
Also changing if($count == 1) to if($count > 0)
or replacing $count = mysql_num_rows($result); if($count == 1) { with if(mysql_num_rows($result) > 0){
Your password is not being hashed
After testing your Adduser code, I noticed is that your hashed password isn't being stored as a hash.
Change ('$_POST[Username]','$_POST[Password]') in your Adduser page to ('$username','$password').
I suggest you move to mysqli with prepared statements, or PDO with prepared statements, they're much safer.
As it stands, your present code is open to SQL injection.
Here is a good site using PDO with prepared statements and password_hash().
http://daveismyname.com/login-and-registration-system-with-php-bp
See also:
CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Try this mate
$query = "select * from customer where name = '" .$username ."' and password = '" .$password ."'";
//use the SANITIZED data
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row) {
$_SESSION['name'] = $row['name'];
$_SESSION['password'] = $row['password'];
}
else { //not found
header('Location: go back.php?error=2');
}
echo "Hello " . $username;