PDO Login System not working - php

I know I'll get a bunch of down-votes, but I am new to PDO and need to make a login system for a little web application. I can't seem to get it right:
<?php
include 'Config.php';
$username = strtolower($_POST['username']);
$password = md5($_POST['password']);
$hidden = $_POST['hidden'];
$submit = $_POST['submit'];
$host = $config['mysql']['host'];
$mysql_user = $config['mysql']['user'];
$mysql_pass = $config['mysql']['pass'];
$db = $config['mysql']['db'];
if(isset($username) && isset($password) && isset($submit) && !isset($hidden)) {
try {
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$objDatabase = new PDO("mysql:host=" . $host . ";dbname=" . $db, $mysql_user, $mysql_pass, $opt);
$objQuery = $objDatabase->prepare("SELECT * FROM users WHERE username=:username");
$objQuery->bindValue(':username', $username);
$objQuery->execute();
$row = $objQuery->fetch(PDO::FETCH_ASSOC);
if(!empty($row)) {
if($username == $row['username'] && $password == $row['password']) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $row['username'];
header('Location: i/');
} else
header('Location: index.php?err=true&type=1');
} else
header('Location: index.php?err=true&type=2');
} catch(PDOException $e) {
die($e->getMessage());
}
}
?>
I always get error 2 - account not found. I'm logging in with user "test" and password "test". In the database is an account with username "test" and the password is an MD5 hash of "test".

Your sql statement is wrong:
SELECT * FROM users WHERE username=':username'
You should not put your placeholder in quotes as now it is taken literally by mysql.
It should be:
SELECT * FROM users WHERE username=:username
You should also tell PDO to throw exceptions:
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$objDatabase = new PDO("mysql:host=" . $host . ";dbname=" . $db, $mysql_user, $mysql_pass, $opt);
So that it will tell you when something goes wrong.
Edit: As noted by #LozCheroneツ you also need to execute the query before you can fetch a row:
$objQuery->bindValue(':username', $username);
$objQuery->execute();

Related

External file with PDO connection not working

I realize this question has been asked in some form or another multiple times, but none of the solutions on the other versions of this question work for me.
These two files have no issues:
/blog/login.php
<?php
include('core/init.php');
if (empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) || empty($password)) {
$errors[] = 'Missing username and/or password.';
} else if (user_exists($username) === false) {
$errors[] = 'User doesn\'t exist.';
}else if (user_active($username) === false) {
$errors[] = 'User account not activated.';
}else {
//
}
print_r($errors);
}
?>
/blog/core/init.php
<?php
require('database/connect.php');
require('functions/users.php');
require('functions/general.php');
session_start();
$errors = array();
?>
I'm just including them to show you how connect.php is require()'d (indirectly) in users.php.
/blog/core/database/connect.php
<?php
$dbname = "xxx_forms";
$servername = "mysql.xxx.com";
$usr= "xxx_xxx";
$pass = "xxxxxxxx";
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $usr, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
This connection itself doesn't trigger any errors...
/blog/core/functions/users.php
<?php
function user_exists($username) {
$ret = '';
try {
$sql = "SELECT COUNT(id) FROM registration WHERE user = '$username';";
$q = $pdo->query($sql);
$f = $q->fetch();
$ret = $f[0];
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
return ($ret == 1) ? true : false;
}
However, when we get to users.php, I always get an error at the $q = $pdo->query($sql); line, apparently because PHP doesn't know what $pdo is. On the other hand, when I include the code from connect.php, so that it is not in an external file (exactly like below, but not commented out):
function user_exists($username) {
//$dbname = "xxx_forms";
//$servername = "mysql.xxx.com";
//$usr= "xxx_xxx";
//$pass = "xxxxxxxx";
$ret = '';
try {
//$pdo = new PDO("mysql:host=$host;dbname=$dbname", $usr, $pass);
$sql = "SELECT COUNT(id) FROM registration WHERE user = '$username';";
$q = $pdo->query($sql);
$f = $q->fetch();
$ret = $f[0];
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
return ($ret == 1) ? true : false;
}
...everything works the way it is supposed to.
How do I make it work when the PDO connection is done in the external file connect.php?
Further to my comment, you need to do something like this:
/config.php
<?php
define('DS',DIRECTORY_SEPARATOR);
define('DB_HOST','localhost');
define('DB_NAME','database');
define('DB_USER','root');
define('DB_PASS','');
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
# Add the connection function
require_once(FUNCTIONS.DS.'connect.php');
# Start session
session_start();
# Get the connection
$pdo = connect();
/functions/connect.php
function connect()
{
$pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
/functions/user_exists.php
<?php
function user_exists($pdo,$username)
{
$ret = 0;
try {
$sql = "SELECT COUNT(id) as count FROM registration WHERE user = :username";
$q = $pdo->prepare($sql);
$q->execute(array(":username"=>$username));
$f = $q->fetch(PDO::FETCH_ASSOC);
$ret = $f['count'];
}
catch (PDOException $e) {
die("Could not connect to the database ".DB_NAME.":" . $e->getMessage());
}
return ($ret == 1);
}
Here is an example of use:
/index.php
<?php
# Add the basic stuff
require(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Add our functions
require(FUNCTIONS.DS.'user_exists.php');
require(FUNCTIONS.DS.'general.php');
# Example of use
print_r(user_exists($pdo,'username#email.com'));

PDO/PHP LoginScript ending in error 500 using MAMP

I've been trying for a while now to get my loginscript working and i can't seem to find the issue, either im just blind or there's something else going on here.
It doesn't matter if i input the correct credentials or not into the form, i still end up getting a lovely error 500.
Any ideas?
The DB connect funtion:
function db_connect() {
if i move this column-->
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
<---
return $conn; /added this as suggested, still returns NULL.
}
The login file:
include('../lib/functions.php'); //This is correct!
db_connect();
<-- HERE, it works -->
Earlier had an issue where my password hash during register was faulty, so password_verify($_POST['password'], $results['passw'])had no effect, always returning false even with correct input.
if(!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT uname,passw FROM users WHERE uname = :user AND passw = :pass');
$records->bindparam(':user', $_POST['username']);
$records->bindparam(':pass', $_POST['password']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($_POST['password'], $results['passw']) && $_POST['username'] == $results['uname']) //Also tried removing the &&-->username area incase two and statements were wrong without any luck {
die('It works!');
} else {
die('OR NOT!');
}
endif;
Your db_connect() function defines $conn in it's own scope. So, variable $conn is local. And after db_connect() ends executing $conn just disappears.
Outside this function $conn is simply NULL.
Return $conn to outer scope from your function:
function db_connect() {
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
return $conn; // here
}
And in your script:
include('../lib/functions.php'); //This is correct!
$conn = db_connect();
// other codes

error with prepare() function

I have this login page that I writes it while watching a tutorial on Udemy. His code works properly, but in my code (the same), I have the following error:
Fatal error: Call to a member function prepare() on a non-object
This is the code:
<?php
//$var = 'This is our first web app page';
//echo $var;
//Connection Variables:
$dbhost = "localhost";
$dbname = "graphic_db";
$dbuser = "root";
$dbpass = "root";
//Connection to SQL:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
//Error messagin enabled:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Adding a character set:
$conn = exec("SET CHARACTER SET utf8mb4");
$user = '';
$pass = '';
$sum = 0;
$error_msg = "Please type a username and a password";
if(isset($_POST['login_submit']))
{
//Start a session:
session_start();
$user = $_POST['username'];
$pass = $_POST['password'];
if(empty($user) && empty($pass))
{
echo $error_msg;
$pass = '';
}
if(empty($user) || empty($pass))
{
echo $error_msg;
$user = '';
$pass = '';
}
if(!empty($user) && !empty($pass))
{
//SQL:
$query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
$query->bindParam(":u", $user);
$query->bindParam(":p", $pass);
//Execute query:
$query->execute();
$number_rows = $query->fetch(PDO::FETCH_NUM);
if($number_rows>0)
{
echo $user;
$_SESSION = $user;
$_SESSION = $pass;
header("Location: /pages/home.php");
}
else
{
echo "Invalid username or password";
header("Location: index.php");
}
//echo $user;
}
}
if(!isset($_POST['login_submit']))
{
echo "Login button not clicked";
}
?>
You destroy the $conn object with this statement:
$conn = exec("SET CHARACTER SET utf8mb4");
Replace it by:
$conn->exec("SET CHARACTER SET utf8mb4");
Note that from PHP 5.3.6 onwards, you can set the character set in the connection string, like this:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpass);
The separate exec call is then no longer necessary.

PHP failing to login - could it the sha256 hashing?

Trying to develop a simple CRUD application piecing together tutorials from the net, just now I'm working on the login and this is proving to be a slight problem. I can register a user and it will add a record to the database, but when I try logging in it fails every time. My code sample is below, any help would be greatly appreciated.
Index.php
require("config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "
SELECT
userid,
username,
password,
salt,
email
FROM wt_users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$login_ok = false;
$row = $stmt->fetch();
if($row){
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password == $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['users'] = $row;
header("Location: secret.php");
die("Redirecting to: secret.php");
}
else{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
config.php
// These variables define the connection information for your MySQL database
$username = "*******";
$password = "***********";
$host = "*********";
$dbname = "********";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
loggedin.php
require("config.php");
if(empty($_SESSION['users']))
{
header("Location: index.php");
die("Redirecting to index.php");
}
Plan is to display a CRUD interface once the user has logged in, but for the moment I can't get them logged in..

PHP validation using PDO not working

I am new to PDO. I have included validation in the following code but it doesnt seem to work and no message appears if users enter the wrong username/password. Please show me where I am going wrong. I have numerous times to get this working but no luck. Thanks
<?php
require("config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$login_ok = false;
$row = $stmt->fetch();
if($row){
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header("Location: secret.php");
die("Redirecting to: secret.php");
}
else{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
Config.php
<?php
// These variables define the connection information for your MySQL database
$username = "xxxx";
$password = "xxxx";
$host = "xxxxxxx";
$dbname = "xxxxxx";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>

Categories