PHP PDO:Login System - php

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.

Related

Convertion from mysql to PDO

So i have decided that its time to modernize my code by updating some of my script from mysql to PDO. Ihave used the last days trying to get to know PDO better, but i cant relate the examples that i have found to my script.
Database Connection:
mysql_connect('localhost', 'root', '') or die ('The server is facing issues at the moment');
mysql_select_db('openchat') or die('Problem with connecting to the database');
Php function with db connection included:
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `username` = '$username'"), 0) == 1) ? true : false;
}
The function checks if the user already exists, where $username is the posted username in a form, and the function checks if the username is taken or not.
I am just showing a small part of the code so i hope this is enough information to get the code :)
Update
I think i finnaly have made an updated version that works!
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=openchat', 'user', 'user123');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
die('The server is facing issues' . '</br>' . $e->getMessage());
}
function test() {
global $db;
$query = $db->query("SELECT COUNT(`user_id`) FROM `user` WHERE `username` = 'testbruker'");
$result = $query->fetchColumn();
return ($result == 1) ? true: false;
}
You can try something like that. But I recommand you to store your DB information in a safe place. But this should do the work.
try{
$db = new Database($host,$username,$password,$database);
$user = 'This user';
$sql = "SELECT COUNT (user_id) FROM users WHERE username = ?;";
$result = $db->prepare($sql);
$result ->execute(array($user));
if ($result ->rowCount() > 0) {
echo 'The user is present';
} else {
echo 'There is nothing';
}
}
catch (Exception $e){
die('Error : ' . utf8_encode($e->getMessage()));
}

PDO Insert not working with bindParam

I am currently using PDO to connect to my database and it works, but when a user logs in, I want it to check if the user's id is already in a row, I have already done this in the code below:
<?php
require 'steamauth/steamauth.php';
if(!isset($_SESSION['steamid'])) {
$username = "Unknown";
$avatar = "defaultUser";
$accid = "Unknown";
$credits = "Not Applicable";
$avatarSmall = "smallUser"; //For Dashboard
} else {
include ('steamauth/userInfo.php');
$username = &$steamprofile['personaname'];
$avatar = &$steamprofile['avatarmedium'];
$accid = &$steamprofile['steamid'];
$avatarSmall = &$steamprofile['avatar']; //For Dashboard
$db_user = "USERNAME";
$db_pass = "PASSWORD";
$db_host = "HOST";
$db_name = "DATABASE NAME";
$db = new PDO("mysql:host=".$db_host.";db_name=".db_name, $db_user, $db_pass);
try{
$check = $db->prepare("SELECT userID from userData WHERE userID = :accountID");
$check->bindParam(':accountID', $accid, PDO::PARAM_INT);
$check->execute();
if(!$check){
die("Server Error: 404Check, Please Contact A Member Of Staff If This Error Continues.");
}else{
if($check->rowCount() > 0) {
$creditsQuery = $db->prepare("SELECT userCredits FROM userData WHERE userID = :accountID3");
$creditsQuery->bindParam(":accountID3", $accid, PDO::PARAM_INT);
$creditsQuery->execute();
//Set Credits To Variable From Database Column
$credits = $creditsQuery->fetch(PDO::FETCH_ASSOC);
}else{
$sql = $db->prepare("INSERT INTO userData (userID, userCredits) VALUES (:accountID2, '0')");
$sql->bindParam(':accountID2', $accid, PDO::PARAM_INT);
$sql->execute();
if(!$sql){
die('Server Error: 404Insert, Please Contact A Member Of Staff If This Error Continues.');
}
}
}
}catch(PDOException $e){
die ("Server Error: 404Connection, Please Contact A Member Of Staff If This Error Continues.");
}
}
?>
Although, when I login, it doesn't seem to store the user's id or credits as 0, and the table (userData) is empty.
Thanks,
Matt
This is wrong:
$check->execute();
if(!$check){
^^^^^^^
$check doesn't magically change into a boolean true/false if the execute fails. It will ALWAYS be a prepared statement object, and therefore always evaluate to true.
You didn't enable exceptions in PDO, therefore it runs in the default "return false on failure" mode, which means your code should be:
$res = $check->execute();
if(!$res) {
die(...);
}
And this holds true for your other prepare/execute blocks as well - Your script is killing itself before it ever gets to the insert query, because your test for database failure is wrong.

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

PHP login script always returns "login failed"

I have to give users the ability to log in for an assignment. At first, it seemed to me this script was simple enough to work, but everytime I try to log in with an existing account it gives me the "login failed" message. I don't know where my mistake lies. It's a PostgreSQL database, I'll enclose an image of it below.
<?php
require 'databaseaccess.php';
try {
$conn = new PDO('pgsql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME,DB_PASSWORD);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "\n";
phpinfo();
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$tablename = "users";
// sql-injection counter
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$qry = $conn->prepare("SELECT * FROM $tablename WHERE userid = :username and userpass = :password");
$qry->bindParam(':username', $username, PDO::PARAM_STR, 16);
$qry->bindParam(':password', $password, PDO::PARAM_STR, 16);
$qry->execute();
$result = pg_query($qry);
$count = pg_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("location:logingelukt.php");
} elseif ($count = -1) {
echo "there has been an error";
} else{
print $count;
echo "login failed";
}
?>
I have no problems connecting to the database, so that's not an issue, it's just that it always sees $count as something else than zero. Another oddity is that the print $count command doesn't output anything.I use the account I made with postgresql outside of the page, which is just admin:admin. Also, I'm sure the right variables are getting passed from the form.
EDIT: After using var_dump($result), as advised by kingalligator, it seems that $result is indeed NULL, thus empty. I'm gonna try using fetch() instead of pg_query().
I think the issue is that you're mixing PDO and pg_ functions.
Replace:
$result = pg_query($qry);
$count = pg_num_rows($result);
With:
$result = $qry->fetchAll();
$count = count($result);
PDO Function reference can be found here: http://www.php.net/manual/en/class.pdostatement.php
Have you confirmed that you're actually getting data returned from your query? Try this:
var_dump($result);
To ensure that data is being returned from your query. You can still have a successful connection to a database, yet have a query that returns nothing.
You probably should check your column userid at WHERE clause. I don't know the table columns, but is strange that 'userid' has the name of the user in:
"SELECT * FROM $tablename WHERE userid = :username and userpass = :password"
Maybe it is causing the problem.

Login users/start session with PDO

Im trying to create a login section on my website using PDO.
So far I've the following...
config.php
// Connect to DB
$username = 'user#site.co.uk';
$password = 'pass';
try {
$conn = new PDO('mysql:host=localhost;dbname=db', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
header.php
// DB Config
include '/assets/config.php';
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
$sth->execute();
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
?>
My browser doesn't display the page however, and when I view my source theres no data contained within, can anybody see where im going wrong?
try this:
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$sth->execute(array(":username" => $login,":password" => $pass));
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
echo $sth->rowCount();
}
make sure you have username "liam" and pass "password" in the database
You have set PDO::ERRMODE_EXCEPTION. This means, you should wrap your statements in a try/catch block and test execute()s return code:
try {
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
if (!$sth->execute()) {
$info = $sth->errorInfo();
echo 'Error: ' . $sth->errorCode() . ' (' . $info[2] . ")\n";
} elseif ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
} catch (PDOException $e) {
echo 'Exception: ' . $e->getMessage() . "\n";
}
and put some trace statements in, of course.

Categories