How can I fix the following code?
function userExists($pdow, $login)
{
$userQuery = "SELECT * FROM login u WHERE login=:user;";
$stmt = $pdow->prepare($userQuery);
$stmt->execute(array(':user' => $login));
return !!$stmt->fetch(PDO::FETCH_ASSOC);
}
$login = 'user';
$exists = userExists($pdow, $login);
if('$login')
$user= var_dump((bool) 'Exists');
{
echo "Login exsists!";
}
I have two problems with my code.
First error:
Error with echoing 'login exsists!'. I see this echo all the time in browser.
Second error:
When I get echo 'login exsists!' my code still inserts data to database.
Simply:
$servername = '';
$dbname = '';
$username = '';
$password = '';
$dbh = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password);
function user_exists($dbh, $Login) {
$Q = $dbh->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':Login', $Login);
$Q->execute();
return $Q->fetch(PDO::FETCH_ASSOC);
}
//Lets try:
$user = user_exists($dbh, 'email#example.com');
if ($user) {
echo 'User: ' . $user['login'] . ' was found in the database.';
} else {
echo 'The user was NOT found.';
}
if($login)
// this line doesnt make any sense!
// $user= var_dump((bool) 'Exists');
// so this is not a valid if clause
{
echo "Login exsists!";
}`
try {
$pdow = new PDO('mysql:host=localhost;dbname=log_cdr', 'root', 'slawek132');
$pdow -> query ('SET NAMES utf8');
$pdow -> query ('SET CHARACTER_SET utf8_unicode_ci');
$pdow->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlw = "INSERT INTO login (login, pass, pass_v, email, email_v)
VALUES ('".$_POST["login"]."','".$_POST["pass"]."','".$_POST["pass_v"]."','".$_POST["email"]."','".$_POST["email_v"]."')";
function user_exists($login) {
$Q = pdow()->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':login', $Login);
$Q->execute();
if ($Q->rowCount() != 0) {
//User exist:
return $Q->fetch(PDO::FETCH_ASSOC);
} else {
//User doesn't exist.
return false;
}
}
Related
I am using SQL(MSSQL) Server database on Windows Server. My database connection is working perfect.
I am trying to get data using Select Query.
Here is my code,
db_functions.php
public function login($username, $password)
{
$sqlString = "SELECT CompId , BUCode , Role from
PRIME_APPUSR WHERE UserName = ? AND PassWord = ?";
$params = array($username, $password);
$stmt = sqlsrv_query($this->conn, $sqlString, $params);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$rows = sqlsrv_has_rows($stmt);
if ($rows === true) {
while ($row = sqlsrv_fetch($stmt)) {
$response["CompId"] = sqlsrv_get_field($stmt, 0);
$response["BUCode"] = sqlsrv_get_field($stmt, 1);
$response["Role"] = sqlsrv_get_field($stmt, 2)
}
return $response;
} else {
return false;
}
}
login.php
<?php
require_once 'db_functions.php';
$db = new db_functions();
if (isset($_POST['USERNAME']) && isset($_POST['PASSWORD'])) {
$USERNAME = $_POST['USERNAME'];
$PASSWORD = $_POST['PASSWORD'];
$result1 = $db->login($USERNAME, $PASSWORD);
if (!$result1) {
$arr["response"] = "Error.";
} else {
$arr["response"] = $result1;
}
echo json_encode($arr);
} else {
$arr["response"] = "Invalid Parameters";
echo json_encode($arr);
}
?>
my question is , i am getting a false in return from this function.
can anyone guide to solve this.?
$sqlString = "SELECT CompId , BUCode, Role from
PRIME_APPUSR WHERE UserName = ? AND PassWord = ?";
I think you need ' , ' between BUCode and Role
I use
password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
for my signup form. It's okay in database save perfectly, but can't login.
This is my login function
public function Login($user, $password)
{
try {
$db = DB();
$query = $db->prepare("SELECT id FROM members WHERE user=:user AND password=:password");
$query->bindParam("user", $user, PDO::PARAM_STR);
$data = $this->query->single();
$getpass = $data['password'];
$passv = password_verify($password, $getpass);
$query->bindParam("password", $passv, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() > 0) {
$result = $query->fetch(PDO::FETCH_OBJ);
return $result->id;
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
EDIT:
login.php
<?php
// Start Session
session_start();
// Database connection
require __DIR__ . '/database.php';
$db = DB();
// Application library
require __DIR__ . 'inc/functions.php';
$app = new DemoLib();
// check Login request
if (!empty($_POST['login'])) {
$user = trim($_POST['user']);
$password = trim($_POST['password']);
if ($user == "") {
echo 'Please enter username.';
} else if ($password == "") {
echo 'Please enter password.';
} else {
$id = $app->Login($user, $password); // check user login
if($id > 0)
{
$_SESSION['id'] = $id; // Set Session
}
else
{
echo 'Wrong data.';
}
}
}
?>
You don't want to try to match the password during the query as matching the hash would not work. In order to verify the password you will want to do something like this:
public function Login($user, $password)
{
try {
$db = DB();
$query = $db->prepare("SELECT * FROM members WHERE user=:user"); // get everything for the user
$query->bindParam("user", $user, PDO::PARAM_STR);
//$data = $this->query->single();
$data = $query->execute();
$getpass = $data['password'];
$passv = password_verify($password, $getpass);
if ($passv) { // if the password is good
return $data['id'];
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
I have this old code that see if session is not registered to destroy it and go back to login page:
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
//if(!session_is_registered(myusername)){
//header("location:index.html");
if(isset($_SESSION['username'])) {
echo "Page seen by " . $_SESSION['username']."<br>";
$con=mysqli_connect($host,$username,$password,$db_name);
mysqli_set_charset($con, 'utf8mb4');
}
else{
session_destroy();
header("location: index.php");
}
?>
I am trying to convert this code to pdo but I can't know how to destroy the session in this method. I just stopped after writing those lines:
<?php
session_start();
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "";
try
{
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Plus, In the following code, always when I click on login it will take me to the next page even if the username and password are incorrect:
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "";
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username != '' && $password!=''){
try{
session_start();
$sql = "SELECT * FROM login WHERE username = :u AND password = :p LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindValue(":u", $username);
$stmt->bindValue(":p", $password);
$exec = $stmt->execute();
$count = $stmt->fetch(PDO::FETCH_ASSOC);
if((count($count)==1)){//&& password_verify($password, $count['password']
$_SESSION['username'] = $username;
header("Location: ./pages/home.php");
}
else {
header("Location: index.php");
}
}
catch(PDOException $e) {
$sql_fail = "INSERT INTO login_attempts(username, password, date_now, time_now)
VALUES (:uf, :pf, :date, now())";
$stmt_fail = $conn->prepare($sql_fail);
$stmt_fail->bindValue(":uf", $username);
$stmt_fail->bindValue(":pf", $password);
$stmt_fail->bindValue(":date", date("y-m-d"));
$exec_fail = $stmt_fail->execute();
header("Location: index.php");
echo $e->getMessage();
}
}
}
?>
I think the key to your login is that you need some little self-contained applications (functions) to break down simple tasks. See if this works better:
/classes/class.PDOConn.php
<?php
class PDOConn
{
// Create a singleton variable to store persistent connection
private static $singleton;
// Set your database credentials here
public static function connect($DB_host = "localhost",$DB_user = "root",$DB_pass = "",$DB_name = "")
{
// first check if the connection has been already set
if(empty(self::$singleton)) {
try {
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
self::$singleton = $conn;
return self::$singleton;
}
catch (PDOException $e) {
die("connection failed");
}
}
// Return the current connection
return self::$singleton;
}
}
/functions/function.query.php
<?php
// This function will make automatic queries to your database
// It accepts a bind array as a second parameter
function query($sql = false,$bind = false)
{
// Create connection
$conn = PDOConn::connect();
// Two ways to query, with and without a bind array
if(!empty($bind) && is_array($bind)) {
$query = $conn->prepare($sql);
$query->execute($bind);
}
else {
$query = $conn->query($sql);
}
// Loop through returned values
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
// Send back array OR send back 0 (for zero results)
return (!empty($result))? $result : 0;
}
/functions/function.write.php
<?php
// This function is the same as query(), just no return array
function write($sql = false,$bind = false)
{
$conn = PDOConn::connect();
if(!empty($bind) && is_array($bind)) {
$query = $conn->prepare($sql);
$query->execute($bind);
}
else {
$conn->query($sql);
}
}
/functions/function.check_user.php
<?php
// This will check the user.
// Do not store plain text passwords
// Instead use password_hash() and password_verify()
function check_user($username,$password)
{
$query = query("SELECT * FROM `login` WHERE `username` = :u LIMIT 1",array(":u"=>$username));
if($query == 0)
return false;
return ($query[0]['password'] == $password);
}
/functions/function.AutoloadFunction.php
<?php
// This is just an autoloader for your functions
// I use it to help cut down on bulk loading of functions
function AutoloadFunction($function = false)
{
// If input is not array, just stop
if(!is_array($function))
return false;
// Set the load folder as this folder
// (all functions should be in the same folder)
$function_dir = __DIR__.'/function.';
// Loop through the array and add the function(s)
for($i = 0; $i < count($functions); $i++) {
// Function name
$addfunction = $functions[$i];
// See if function exists
if(!function_exists($addfunction)) {
$dir = $function_dir.$addfunction.'.php';
if(is_file($dir)) {
include_once($dir);
}
}
}
}
login.php
<?php
// Session start regardless
session_start();
// Check if login attempted
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
// If user or pass is empty OR there is already a session, just stop
// You may want to do a redirect here, not sure....
if(empty($username) || empty($password) || !empty($_SESSION['username']))
return false;
// Include the autoloader function
include_once(__DIR__.'/functions/function.AutoloadFunction.php');
// Maybe look into using spl_autoload_register() to autoload classes
include_once(__DIR__.'/classes/class.PDOConn.php');
// Autoload functions
AutoloadFunction(array("check_user","write","query"));
// Verify with handy-dandy function
if(check_user($username,$password)) {
$_SESSION['username'] = $username;
$location = "./pages/home.php";
}
// Write the attempt
else {
write("INSERT INTO `login_attempts` (`username`, `password`, `date_now`, `time_now`) VALUES (:uf, :pf, :date, NOW())",array(":uf"=>$username,":pf"=>$password,":date"=>date("y-m-d")));
$location = "index.php?errror=invalid";
}
// Forward
header("Location: {$location}");
exit;
}
Use the code in this link here.
You should use fetch(PDO::FETCH_NUM) so your code will be something like this:
$result = $conn->prepare("SELECT * FROM users WHERE username= :hjhjhjh AND password= :asas");
$result->bindParam(':hjhjhjh', $user);
$result->bindParam(':asas', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0) {
header("location: home.php");
}
else{
$errmsg_arr[] = 'Username and Password are not found';
$errflag = true;
}
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php");
exit();
}
I am implimenting RBAC system but prlomlem cant get id and store in session
in the following code error at :
Fatal error: Call to a member function prepare() on a non-object in
C:\wamp\www\CRM\login.php on line 19
Here is my code block:
<?php
require('connection.inc.php');
require_once "Role.class.php";
require_once "User.class.php";
session_start();
$username = $_POST['username'];
$password = $_POST['userpwd'];
if(!empty($username) ) // && $_SESSION['username'] == ''
{
try
{
$stmt = $dbhandle->prepare('SELECT `user_id` FROM `user` WHERE `username` = :username');
$stmt->execute(array('username' => $username));
$result = $stmt->fetchAll();
if (count($result))
{
foreach ($result as $row)
{
echo $row['user_id'];
$_SESSION['user_id'] = $row['user_id'];
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if(isset($_SESSION["user_id"]))
{
$user = new User($_SESSION["user_id"]);
if ($user->hasPermission("permission"))
{
//This user is allowed to do this
header("Location: dashbord.php");
exit();
}
if ($user->hasPermission("no_permission"))
{
//This user is NOT allowed to do this
header("Location: index.php");
}
}
}
else
{
?>
<script type="text/javascript">
alert('ERROR:Please enter your username and password');
//window.location=".html";
</script>
<?php
}
?>
UPDATE-1:
First update your connection.inc.php file as below:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "test";
try{ //connection to the database
// you missed 'mysql:host=$hostname;dbname=$dbname'.
$dbhandle = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
}
catch(PDOException $e) { echo $e->getMessage(); }
?>
Now, Your main query page :
try{
$query ="SELECT user_id FROM user WHERE username = ?";
$stmt = $dbhandle->prepare($query);
$stmt->bindParam(1, $username ); // bind the username
$stmt->execute(); // execute query
// returning rows form database
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['user_id']; // echo to varify the row data
$_SESSION['user_id'] = $row['user_id']; // can not understand why you make session for each user_id
}
}
catch(PDOException $e){ echo $e->getMessage();}
Bind the value you are searching for, and check for if you get rows returned.
$stmt = $this->db->conn->prepare('SELECT `user_id` FROM `user` WHERE `username`=:username');
$stmt->execute(array('username' => $username));
$result = $stmt->fetchAll();
if (count($result)) {
foreach ($result as $row) {
echo $row['user_id'];
$_SESSION['user_id'] = $row['user_id'];
}
} else {
echo "No rows returned.";
}
I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.