Error creating login system php - php

I've been trying to create a php login system but I can't make it work as if I try to login with valid username and password it will say "fail". I've using this technique before and was successful but this time I can't make it work.
Code:
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$conn = new PDO("mysql:host=localhost;dbname=login" ,'root','');
if (!$conn){
die("Not connected". mysqli_connect_error());
}else {
echo "Connection sucessfull";
echo "</br>";
}
$sql = "select * from details where Username=$username and Password=$password";
$stmt=$conn->prepare($sql);
$stmt->bindparam("Username",$username,PDO::PARAM_STR);
$stmt->bindparam("Password",$password,PDO::PARAM_STR);
$stmt->execute();
$num = $stmt->rowCount();
if ($num>0){
echo "You are logged in";
}else {
echo "fail";
}
Thanks

Your statement should go like this:
$stmt= $conn->prepare("SELECT * FROM `details`
WHERE `Username`=:username AND `Password`=:password");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
Note:
According to php.net PDOStatement::rowCount() returns the number of
rows affected by the last DELETE, INSERT, or UPDATE statement executed
by the corresponding PDOStatement object.
So for counting the number of rows returned by select statement, you can use fetchAll():
if (count($stmt->fetchAll()) > 0) {
echo "You are logged in";
}else {
echo "fail";
}
And for setting smart PDO connection:
try {
$db_host = '';// hostname
$db_name = '';// databasename
$db_user = '';// username
$user_pw = '';// password
$conn = new PDO('mysql:host='.$db_host.'; dbname='.$db_name, $db_user, $user_pw);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$conn->exec("SET CHARACTER SET utf8");
}catch (PDOException $err) {
echo "harmless error message if the connection fails";
$err->getMessage() . "<br/>";
file_put_contents('PDOErrors.txt',$err, FILE_APPEND);//log errors
die(); // terminate connection
}

I've formatted your code and it should work now. You cannot mix mysqli_* with PDO.
$conn = new pdo("mysql:host=localhost;dbname=login;", 'root', '');
if ($conn->connect_error) {
die("Not connected" . $conn->connect_error);
}
echo "Connection successful<br/>";
$sql= "select * from details where Username=:username and Password=:password";
$result = $connection->prepare($sql);
$result->bindParam(":username" ,$_POST['username']);
$result->bindParam(":password" ,$_POST['password']);
$result->execute();
$num=$result->fetchColumn();
if($num > 0){
header("location:index.php");
}else{
header("location:login.php");
}

Related

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $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();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

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();
}
?>

Checking if Username and Password are correct

As my code is right now, I always get the echo "Username/Password incorrect."; whether or not the username/password match or not. My question is, What did I do wrong in the code below for the php to always echo "Username/Password incorrect"
<?php
require 'privstuff/dbinfo.php';
$password1 = $_POST["password1"];
$username = $_POST["username"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Connection Failed. Please send an email to owner#othertxt.com regarding this problem.";
exit();
}
if ($stmt = $mysqli->prepare("SELECT username, password FROM accounts WHERE username=? and password=?")) {
$db_pw = password_hash($password1, PASSWORD_BCRYPT);
$stmt->bind_param("ss", $username, $db_pw);
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo "Logged in.";
}else{
echo "Username/Password incorrect.";
}
$stmt->close();
}
$stmt->close();
$mysqli->close();
?>
Update I've changed if ($stmt->affected_rows > 0) to if ($stmt->num_rows). Still doesn't work though
UPDATE 2 I've realized the issue is me using password_hash($password1, PASSWORD_BCRYPT); I didn't realize that the hash gives different strings every time. I'm not understanding on how to use password_verify
The documentation of mysqli_stmt_affected_rows() says:
This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows() instead.
You also need to call mysqli_stmt_store_results() first, to buffer the results.
$stmt->store_results();
if ($stmt->num_rows > 0) {
...
}
I figured it out. I was not supposed to use password_hash again. I didn't realize that using password_hash gave different results. I then changed it to use password_verify.
<?php
require 'privstuff/dbinfo.php';
$username = $_POST["username"];
$password1 = $_POST["password1"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT `password` FROM `accounts` WHERE username = ?")) {
/* Bind parameters: s - string, b - blob, i - int, etc */
$stmt -> bind_param("s", $username);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
}
if(password_verify($password1, $result))
{
echo("Hello");
}else{
echo("No-Go");
}
$mysqli->close();
?>

Login script using PDO extension not working

I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>

Categories