PHP and SQlite: Login - php

I need to do a Login form with PHP an SQlite. Registration works, and I can select all created users and echo them. When I try to check if username and password, which I get by $_POST, are matching: it echoes that I'm logged in now. But when I type in a wrong user/pw, it echoes the "invalid"-string, but there's also the following error:
Notice: Undefined variable: row in D:\xampp\htdocs\phpProjektSnippets\blogLogin.php on line 17
Line 17 is where I've got the if($row['username'] ...
This is my code:
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE user_name = :name AND user_password = :pass";
$statement = $db->prepare($sql);
$statement->execute(array('name' => $username, 'pass' => $password));
try {
$statement = $db->prepare($sql);
$statement->execute(array('name' => $username, 'pass' => $password));
foreach ($statement as $row);
if ($row['user_name'] == $username && $row['user_password'] == $password){
echo "Welcome " .$row['user_name']. ", You are now logged in.<br/ >";
}else{
echo "User Name or Password is invalid";
}
}
catch(PDOException $e) {
echo "Something went wrong: ".$e->getMessage();
}
What's wrong here?

First of all, you should not use an SQL query that looks like yours. It is vulnerable for SQL injections and thereby unsafe!
Please read the answers on How can I prevent SQL-Injection in PHP for some very helpful tips on how to do it right.
The problem is that you append to the SQL string whatever the user submits to the server - that might be malicious code that gives an attacker access to your database or deletes data or other bad things might happen. See the link above for more information.
In your case, the code would look like this:
<?php
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT * FROM users WHERE user_name = :name ";
try {
$statement = $db->prepare($sql);
$statement->execute(array('name' => $username));
foreach ($statement as $row){
echo $row['user_name'] . '<br />';
}
}
catch(PDOException $e) {
echo "Something went wrong: ".$e->getMessage();
}
?>
Edit: Since you configured PDO with $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ) to throw exceptions in case of an error, you should also catch them. I added the try/catch to the code.

Adding to Hexaholic answer and further to your question.
This line catch your code error
catch(PDOException $e) {
echo "Something went wrong: ".$e->getMessage();
}
If you want to write error in case of invalid user credentials,
use if true...else...statement.
if(some argument){
//do something if the argument result is true;
}else{
do something if the argument is not true;}
So your code should be something like this.
<?php
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE user_name = :name AND user_password = :pass";
try {
$statement = $db->prepare($sql);
$statement->execute(array('name' => $username, 'pass' => $password));
$row = $statement->fetch();
if ($row['user_name'] == $username && $row['user_password'] == $password){
echo "Welcome " .$row['user_name']. ", You are now logged in.<br/ >";
}else{
echo "User Name or Password is invalid";
}
}
catch(PDOException $e) {
echo "Something went wrong: ".$e->getMessage();
}
?>
And if this is working, remember to rectify your hashing issue.
Maybe this picture can better help you understand for the code above
Wrong password output.
Correct password output.

Trouble is with semicolon in this line: foreach ($statement as $row);
Foreach simply does nothing instead of subsequent if.

Related

Doesn't insert data in DB

Almost 2 days my computer doesn't want to insert data in my DB, tried to change a lot in code but still not works. (and deleted ` - and nothing changed). Could you suggest what is the reazon?
<?php
include '../db.php';
try {
$stmt = $dbh->prepare(" INSERT INTO `users` (`login`,`password`) VALUES (:login, :password) ");
$stmt->bindParam(':login', $login );
$stmt->bindParam(':password', $password );
$_POST['login'] = $login;
$_POST['password'] = $password;
$stmt->execute();
}
catch (exeption $e) { // Если ошибка - показать сообщение об ошибке
echo $e->getMessage();
}
echo "\nPDO::errorCode(): ", $dbh->errorCode();
echo " ";
$rows = $stmt->fetchAll();
$num_rows = count($rows);
echo $num_rows;
/*header("location:../auth.php");*/
?>
Returns PDO::errorCode(): 00000 (thats fine), but it returns 0 rows! Maybe that's the reason
And my db.php file:
<?php
try { //Connecting to db via login and password
$user = 'mydatabases';
$pass = '1234';
$dbh = new PDO('mysql:host=localhost;dbname=dbname', $user, $pass);
}
catch (exeption $e) { //if any mistakes show message of error
echo $e->getMessage();
}
?>
In my DB was 2 extra columns I wanted them to be empty (they didnt fill when user register), that was the reason why code didnt work and didnt send me any error messages

Coverting PHP login script to use prepared statements

I'm trying to learn to convert a PHP login page to use prepared SQL statements with parameters versus just using standard script to protect from SQL injection. Its for a security class and not a programming class and my PHP is weak and be will evident. I can't figure out why I'm not getting any results from the execution. Its using PDO, and I've switch from bindParam to bindValue as suggested on other topics, but I still get a black page from the login.
My db connection is working, and I think my SQL statement and parameters are correct. I really believe the problem is in retrieving the results. Can anyone help why I can get a row count? I've also tried with $stmt->count_rows
<html>
<body>
<?php
$db_hostname = 'localhost';
$db_username = 'testuser';
$db_password = '1234';
$db_dbname = 'testdb';
$db_tablename = 'users';
$db_conn_str = "mysql:host=" . $db_hostname . ";dbname=" . $db_dbname;
try {
$db = new PDO($db_conn_str, $db_username, $db_password);
$stmt = $db->prepare("Select * from users where login = ? and passwd = ?");
$stmt->bindValue(1, $_POST['username']);
$stmt->bindValue(2, $_POST['password']);
$stmt->execute();
$stmt->store_result();
$result = $stmt->fetchAll();
$num = $result->rowCount();
$stmt->close();
}
catch (PDOException $e) {
echo "Error in PDO: " . $e->getMessage();
}
if ($num == 0) {
echo "login failed! <br />";
} else {
$name = $result->fetchColumn(0);
echo "Welcome, $name!<br />";
}
?>
A few issues.
Syntax error after $db_hostname='localhost'
PDO does not have a store_result() method, that's a mysqli method.
Turn off emulated prepared querys. ATTR_EMULATE_PREPARES
You need to also tell PDO to throw Exceptions else it wont ERRMODE_EXCEPTION
Also $result->fetchColumn(0); will fetch the first column so presuming that id your welcome message would say Welcome, 1.
Just count fetchAll() instead of rowCount().
Don't forget htmlentities() to protect against stored XSS
Below is changed code:
<?php
$db_hostname='localhost';
$db_username='testuser';
$db_password='1234';
$db_dbname='testdb';
$db_tablename='users';
$db_conn_str="mysql:host=" . $db_hostname . ";dbname=" . $db_dbname;
try {
$db = new PDO($db_conn_str, $db_username, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->prepare("SELECT * FROM users WHERE login = ? AND passwd = ?");
$stmt->bindValue(1, $_POST['username']);
$stmt->bindValue(2, $_POST['password']);
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) == 0) {
echo "login failed! <br />";
} else {
echo "Welcome, ".htmlentities($result[0]['name'])."!<br />";
}
$stmt->close();
} catch (PDOException $e) {
echo "Error in PDO: " . $e->getMessage();
}
?>
You should also look into using password_* based functions instead of storing your passwords as plaintext.
Hope it helps.

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

How do I make an if statement which checks if a variable is in the mysql database

try {
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'"; // SQL Query
$conn->exec($sql);
Thats some of my code, how do I make it so if suser and shashpass are correct it can
execute some code, else it executes other code
This won't work either
<?php
try
{
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password"); $query->bindParam(':user',$suser);
$query->bindParam(':password',$shashpass); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){ } else { } }
catch(PDOException $e) {
echo $sql . $e->getMessage();
}
You don't pre-hash the password when verifying it. Instead you SELECT the password hash from that user (if it exists) and then use password_verify() to verify that it's correct based on the plain text password sent by the web form.
$stmt = $conn->prepare("SELECT password FROM us WHERE username=?");
$stmt->execute([$suser]);
if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (password_verify($plain_text_password, $user['password'])) {
// Successful login
}
else {
// Valid user, but invalid password
}
}
else {
// User doesn't exist
}
If you're not using password_hash() and password_verify(), You're Doing It Wrong™.
you are using PDO in wrong way , you need to use prepared statements in PDO to be secure from mysql injections, try to use the code below:
try {
$conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password");
$query->bindParam(':user',$suser);
$query->bindParam(':password',$shashpass);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
// user is in database
} else {
// user is not there
}
exec will return the number of affected rows so:
$rows = $conn->exec($sql);
if($rows > 0){
//suser and shashpass are correct
}else{
//suser and shashpass are incorrect
}
//Use below PDO code
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'";
// SQL Query
$conn->exec($sql);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

PHP PDO:Login System

I am working on a PHP PDO Login system but i keep getting an error, perhaps some part of my code is incorrect.
//LOG IN VERIFICATION
if (isset($_POST['username'],$_POST['pass'])) {
try {
$con = new PDO("mysql:host=" . host . ";dbname=" . database, user, auth);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_POST['username'])&& !empty($_POST['pass'])) {
//username and password sent from Form
$usernames = trim($_POST['username']);
$password = $_POST['pass'];
$select= $con -> prepare("SELECT username,password FROM users WHERE username='$username' AND password='$password'");
$select ->execute();
$results = $select->fetch(PDO::FETCH_ASSOC);
if (count($results) > 0 && password_verify($password, $results['password'])) {
header('location:home.php');
} else{
header('location:login.php');
}
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
I suspect the error to be here
$select= $con -> prepare("SELECT username,password FROM users WHERE username='$username' AND password='$password'");
$select ->execute();
$results = $select->fetch(PDO::FETCH_ASSOC);
because i verified the connection to the database. Any help will be appreciated.
You're assigning to $usernames, not $username. However, the real problem is count($results) - you cannot count the rows this way. Which means, the count will be 0, hence the else branch is executed. See here: Row count with PDO.
Edit: In such cases, simply debug your code and var_dump(count($results)), for example. You have a simple if statement - if an unexpected branch is executed, something is wrong with the if condition.

Categories