Login users/start session with PDO - php

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.

Related

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 is not displaying any data on my web page

I've recently tried to convert my procedural MySQL queries to PDO statements. I've copied the following code from php official documentation and added my parameters to it. It is not showing any results in the page.
<?php
$dsn = 'mysql:host=localhost;dbname=database';
$user = 'user';
$pass = 'pass';
try {
$dbh = new PDO($dsn , $user, $pass);
$dbh = null;
} catch (PDOException $e) {
print "An error has occurred. Please contact support. <br/>" . $e->getMessage() . "<br/>";
die();
}
$value = 'user1';
$stmt = $dbh->prepare("SELECT * FROM table where username = ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
?>
Try this:-
<?php
$dsn = 'mysql:host=localhost;dbname=databasename';
$user = 'user';
$pass = 'password';
try {
$dbh = new PDO($dsn , $user, $pass);
} catch (PDOException $e) {
print "An error has occurred. Please contact support. <br/>" .
$e->getMessage() . "<br/>";
die();
}
$value = 'user1';
$stmt = $dbh->prepare("SELECT * FROM table where column= ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>

Why are users who do not exist allowed to login using this bit of script?

I have some PDO:
if (empty($this->user->username) || empty($this->user->password))
throw new Exception("Error Processing Request", 1);
include('dbconnect.php'); // Normally I'd store the db connect script outside of webroot
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('SELECT userFName FROM Users WHERE username = ? AND password = ? AND roleID = 1');
$stmt->bindParam(1, $this->user->username);
$stmt->bindParam(2, $this->user->password);
$stmt->bindColumn(1, $userFName, PDO::PARAM_STR);
try {
$stmt->execute();
}
catch (PDOException $e) {
echo 'Invalid username or password: ' . $e->getMessage();
}
$stmt->fetch(PDO::FETCH_BOUND);
$this->user->firstName = $userFName;
If the POSTed username and/or password are wrong, a login still occurs. I think something is wrong with the PDO; did I miss something critical when trying to check $this->user->password against the record in the DB?
(btw, I am using encryption)
$stmt->execute();
will not throw an exception if there are no results. You need to check if the query result returned a row for the user.
edit:
$stmt->execute();
if ($stmt->rowCount() > 0) {
//user found
} else {
//user not found
}

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