When i try to verify user data by verify_user method
<?php
public static function verify_user ($username , $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$query = "SELECT * FROM users WHERE username = '{$username}' and password = '{$password}' LIMIT 1";
$result_array = self::find_this_query($query);
if (!empty($result_array)) {
$result_array = array_shift($result_array);
return $result_array;
} else {
return false;
}
}
here also my find_this_query method
public static function find_this_query ($enter_here_your_sql_query)
{
global $database;
$result = $database->query($enter_here_your_sql_query);
return $result;
}
and try to login a user here also my login.php code
<?php
if($session->is_signed_in()) {
redirect("index.php");
}
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
//method to check db user
$user_found = User::verify_user($username , $password);
if ($user_found) {
$session->login($user_found);
redirect("index.php");
} else {
$the_message = "<p class='alert alert-warning' style='color: grey'>Your password or username is incorrect</p>";
$username = "";
$password = "";
}
?>
i get that error on login page
Warning: array_shift() expects parameter 1 to be array, object given in /admin/includes/User.php on line 189
here line 189 from user.php class
$result_array = array_shift($result_array);
What i do wrong here?
$database->query() does not return an array, it returns an object. Try using $database->fetch_array().
The mysqli::query() function doesn't return an array, it returns a mysqli_result object.
mysqli_result implements the Traversable interface, which allows you to use some array operations on it like foreach, but most other array operations don't work. In particular, you can't use array_shift() on this object.
Instead of
$result_array = array_shift($result_array);
return $result_array;
use:
$row = $result_array->fetch_assoc();
return $row;
i solve that issue by the Help give me Barmar.
Here my updated verify_user function
public static function verify_user ($username , $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$query = "SELECT * FROM users WHERE username = '{$username}' and password = '{$password}' LIMIT 1";
$result_array = self::find_this_query($query);
if (!empty($result_array)) {
$result_array = $result_array->fetch_array();
return $result_array;
}else{
return false;
}
}
and here my updated login.php
if($session->is_signed_in()) {
redirect("index.php");
}
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
//method to check db user
$user_found = User::verify_user($username , $password);
$user = User::instantiation($user_found);
$user_id = $user->id;
if ($user_id){
$session->login($user);
redirect("index.php");
} else {
$the_message = "<p class='alert alert-warning' style='color: grey'>Your password or username is incorrect</p>";
$username = "";
$password = "";
}
Related
Okay so heres the issue, I am trying to making a fancy login system that stores the users data in a php class so it is easy to access. However when I try to call the function that will build the user data it throws this exception.
Fatal error: Uncaught Error: Call to a member function buildUserData() on string in C:\xampp\htdocs\cfgs\submit\login.php:38 Stack trace: #0 {main} thrown in C:\xampp\htdocs\cfgs\submit\login.php on line 38
Here is the userData class code
<?php
class userData {
public $accId = null;
public $username = null;
public $rank = null;
public $vip_rank = null;
public $email = null;
public $auth = null;
function buildUserData($id) {
$result = $db->query("SELECT * FROM users WHERE id = '$id'");
while ($row = $result->fetch_assoc()) {
$this->accId = $id;
$this->username = $row['username'];
$this->rank = $row['rank'];
$this->vip_rank = $row['rank_vip'];
$this->email = $row['mail'];
$this->auth = $row['auth'];
}
}
}
?>
This is the login.php code
<?php
require_once '../../global.php';
if(!isset($_POST['submit'])) {
header("Location: ../../index");
return;
} else {
$user = $db->escapestring($_POST['user']);
$pass = $db->escapestring($_POST['pass']);
if (empty($user) || empty($pass)) {
$_SESSION['logError'] = "Both fields must be filled!";
header("Location: ../../index");
return;
} else {
$result = $db->query("SELECT * FROM users WHERE username = '$user'");
$result = $db->getrows($result);
if ($result < 1) {
$_SESSION['logError'] = "Username does not exist!";
header("Location: ../../index");
return;
} else {
$pass = md5($pass);
$result = $db->query("SELECT * FROM users WHERE username = '$user' AND password = '$pass'");
$result = $db->getrows($result);
if ($result < 1) {
$_SESSION['logError'] = "Details do not match!";
header("Location: ../../index");
return;
} else {
$result = $db->query("SELECT * FROM users WHERE username = '$user' AND password = '$pass'");
while($row = $result->fetch_assoc()){
$username = $row['username'];
$id = $row['id'];
}
$user->buildUserData($id);
$_SESSION['logError'] = "Hello ". $user->username;
header("Location: ../../index");
return;
}
}
}
}
?>
This is the global.php code
<?php
session_start();
require_once 'cfgs/class.database.php';
require_once 'cfgs/class.user.php';
$user = new userData; // I don't want to build data just yet
$db = new database;
$db->conn = $db->connect();
?>
And finally my database handler
<?php
class database {
public $host = "_";
public $user = "_";
public $pass = "_";
public $db = "_";
public $conn = null;
function connect() {
return mysqli_connect($this->host, $this->user, $this->pass, $this->db);
}
function query($sql) {
return mysqli_query($this->conn, $sql);
}
function escapestring($string){
return mysqli_real_escape_string($this->conn, $string);
}
function getrows($sql){
return mysqli_num_rows($sql);
}
}
?>
I did search for a solution myself but it turns out to be one of those specific things that is difficult to find the answer you're looking for.
while you initialise $user just fine:
$user = new userData;
you later overwrite the variable:
$user = $db->escapestring($_POST['user']);
one of the 2 needs a new name,
am trying to get the id in another page bu i always got nulls whats wrong with my code here ? and how to fix it ?
** the problem is in ->
public function login($email, $password) {
$db = new database(); //connection with database
$q = "select * from user where
email='$email'
AND
password='$password'";
$db->pQuery($q);
$userSet = $db->fetchAll();
// var_dump($userSet);die;
if (!empty($userSet)) {
// session_start();
$_SESSION["username"] = $email;//not null
$_SESSION["userid"] = $userSet['id'];//null
print_r( $_SESSION["userid"]);
var_dump($_SESSION["userid"]);die;
header("location:search.php");
exit();
} else {
return false;
}
}
in the other page :
<?php
session_start();
$id = $_SESSION['userid'];//==null
echo $id;//null here
var_dump($id);//null here
Because you are using fetchAll() which return an array of array.
$userSet = $db->fetchAll();
if (!empty($userSet)) {
$_SESSION["username"] = $email;
$_SESSION["userid"] = $userSet[0]['id']; // <<< Add [0]
Or use fetch() instead of fetchAll():
$userSet = $db->fetch();
if ($userSet) {
$_SESSION["username"] = $email;
$_SESSION["userid"] = $userSet['id'];
I have defined a function to check user credentials and would like it to return true if the auth passed and false if it failed. my function is defined as follows:
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
return $logged_in;
}
the problem I am running into is this, when I call the function and try to use what should be the returned value I get an error that the variable is not defined.
_userLogin($username, $password);
if ($logged_in == True){
'do something';
} else {
'do something else'
}
what am I doing wrong?
You are trying to use the variable $logged_in that is defined in function _userLogin outside the block. Assign the return value that is returned by the function like,
$logged_in = _userLogin($username, $password)
if ($logged_in == True){
'do something';
} else {
'do something else'
}
Also you will always receive TRUE because you are accessing variables $salt, $password outside the if block where they are being retrieved thus the fields not being assigned properly.
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in = false;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
$dbpass = '';
$salt = '';
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
}
}
return $logged_in;
}
PLEASE NOTE: I did not perform any logic checks other than fix your syntax
Replace your branching (where you use the function) with the simpler:
if( _userLogin($username, $password) ){
//success
}else{
//failure
}
I have problem with get data from database.
This is my function:
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
var_dump(mysql_result($result));
if(mysql_result($result)>0){
//$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
else{
print_r('chuj');
}
}
and this is my function call:
$uid = $_SESSION['uid'];
$user = new User();
$register = $user->get_fullname($uid);
What is wrong with my code?
Full class in file Functions.php:
include_once 'config.php';
class User
{
//Połączenie z bazą danych
public function __construct()
{
$db = new DB_Class();
}
//Rejestracja
public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}
//Logowanie
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
var_dump($_SESSION);
return TRUE;
}
else
{
return FALSE;
}
}
//Pobieranie imienia
public function get_fullname($uid)
{
$result = mysql_query("SELECT * FROM users WHERE uid ='".$uid."'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if($no_rows>0){
$user_data = mysql_fetch_array($result);
//echo $user_data['name'];
return $user_data['name'];
}
else{
print_r('chuj');
return FALSE;
}
}
//Sesja
public function get_session()
{
return $_SESSION['login'];
}
//Wylogowanie
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
Fatal error: Call to undefined method User->get_fullname()
Rizier123's comment is correct, but not the cause of your problem.
I tried to reproduce the error but failed. That means that probably you're using an old version somewhere. If you're using FTP or the like, are you sure you uploaded the User class since you added the function?
Also, make sure that the most recent User class is included in the file where you're using it.
So, when I run this login script, I get the following error:
PHP Warning:
mysql_real_escape_string() [function.mysql-real-escape-string]:
A link to the server could not be
established in (...) on line 116.
I'm calling the database at the top of the script, and not getting any errors from PEAR... print_r($db) returns an object...
code follows:
<?php
function &db_connect() {
require_once 'DB.php';
PEAR::setErrorHandling(PEAR_ERROR_DIE);
$db_host = 'internal-db.xxxxx.gridserver.com';
$db_user = 'xxxxx';
$db_pass = 'xxxx';
$db_name = 'xxxxx_wedding2';
$dsn = "mysqli://$db_user:$db_pass#$db_host/$db_name";
$db = DB::connect($dsn);
$db->setFetchMode(DB_FETCHMODE_OBJECT);
return $db;
}
$db = &db_connect();
if (DB::isError ($db))
die ("Cannot connect: " . $db->getMessage () . "\n");
if (!isset($_SESSION['uid'])) {
session_defaults();
}
function session_defaults() {
$_SESSION['logged'] = false;
$_SESSION['uid'] = 0;
$_SESSION['username'] = '';
$_SESSION['cookie'] = 0;
$_SESSION['remember'] = false;
}
class User {
var $db = null; //PEAR::DB pointer
var $failed = false; //failed login
var $date; //current date
var $id = 0; //current users id
function User(&$db) { //is this the constructor?
$this->db = $db;
$this->date = $GLOBALS['date'];
$this->role = $_SESSION['role'];
if ($_SESSION['logged']) {
$this->_check_Session();
} elseif (!isset($_COOKIE['myLogin'])) {
$this->_checkRemembered($_COOKIE['myLogin']);
}
}
function _checkLogin($username, $password, $remember) {
$username = $this->db->quote($username); //uses PEAR::DB->quote method to sanitize input
$password = $this->db->quote(md5($password)); // " "
$sql = "SELECT * FROM guest WHERE (username = $username) AND (password = $password)";
$result = $this->db->getRow($sql);
if (is_object($result)) {
$this->_setSession($result, $remember);
return true;
} else {
$this->failed = true;
$this->_logout();
print "Sorry, you have entered an invalid username or password!";
return false;
}
}
function _checkRemembered($cookie) {
list($username, $cookie) = unserialize($cookie);
if (!$username or !$cookie) return;
$username = $this->db->quote($username);
$cookie = $this->db->quote($cookie);
$sql = "SELECT * FROM member WHERE (username = $username) AND (cookie = $cookie)";
$result = $this->db->getRow($sql);
if (is_object($result)) {
$this->_setSession($result, true);
}
}
function _setSession(&$values, $remember, $init = true) {
$this->id = $values->id;
$_SESSION['uid'] = $this->id;
$_SESSION['username'] = htmlspecialchars($values->username);
$_SESSION['cookie'] = $values->cookie;
$_SESSION['logged'] = true;
$_SESSION['role'] = $values->role;
if ($remember) {
$this->updateCookie($values->cookie, true);
}
/* if ($init) {
$session = $this->db->quote($_SERVER['REMOTE_ADDR']);
$sql = "UPDATE guest SET session = $session, ip = $ip WHERE id = $this->id";
$this->db->query($sql);
}*/
}
function updateCookie($cookie, $save) {
$_SESSION['cookie'] = $cookie;
if ($save) {
$cookie = serialize(array($_SESSION['username'], $cookie));
set_cookie;}
}
}
function _logout() {
session_defaults();
}
$date = time();
$user = new User($db);
$myusername = mysql_real_escape_string(stripslashes($_POST['myusername']));
$mypassword = mysql_real_escape_string(stripslashes($_POST['mypassword']));
$status = $user->_checkLogin;
print_r($status);
Any thoughts what I'm missing here? Is there a better way to troubleshoot my db connection?
Thanks in advance.
Please read mysql_real_escape_string() documentation. You should provide link to connection with mysql as 2nd argument.
Updated: if you want to store user's data to database, so why not use prepare() from PEAR::DB? It effectively protect you from SQL-injection.