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,
Related
I want to make login and registration in my UWP app using PHP and MySQL
I use this code below to do it but it didn't work
I try many ways in internet but its so old
I make PHP and MySQL Database in a localhost xampp
I'm beginner in PHP so pleas anyone tell me the error in my code
I use this code to POST data to serve in UWP :
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri requestUri = new Uri("http://localhost/test/index.php");
HttpStringContent stringContent = new HttpStringContent
(" { \"email\": \"" + emailbox.Text + "\" , \"password\":\"" + passwordbox.Text + "\" } "
, Windows.Storage.Streams.UnicodeEncoding.Utf8
, "application/json");
//Dictionary<string, string> pairs = new Dictionary<string, string>();
//pairs.Add("email", emailbox.Text);
//pairs.Add("password", passwordbox.Text);
//HttpFormUrlEncodedContent encodedContent = new HttpFormUrlEncodedContent(pairs);
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();
await client.PostAsync(requestUri, stringContent);
}
And This is my PHP backend code
config.php
<?php
define("DB_HOST","127.0.0.1");
define("DB_USER","root");
define("DB_PASSWORD","");
define("DB_NAME","firstdb");
?>
db_connect.php
<?php
include_once 'config.php';
class DbConnect{
private $connect;
public function __construct(){
$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($this->connect)){
echo "Unable to connect to MySQL Database: " . mysqli_connect_error();
}
}
public function getDb(){
return $this->connect;
}
}
?>
user.php
<?php
include_once 'db_connect.php';
class User{
private $db;
private $db_table = "users";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($email, $password){
$query = "select * from ".$this->db_table." where email = '$email' AND password = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function isEmailUsernameExist($email){
$query = "select * from ".$this->db_table." where email = '$email'";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
return false;
}
public function isValidEmail($email){
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
public function createNewRegisterUser( $email, $password){
$isExisting = $this->isEmailUsernameExist($email);
if($isExisting){
$json['success'] = 0;
$json['message'] = "Error in registering. Probably the username/email already exists";
}
else{
$isValid = $this->isValidEmail($email);
if($isValid)
{
$query = "insert into ".$this->db_table." (email, password) values ('$email','$password')";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
$json['message'] = "Successfully registered the user";
}else{
$json['success'] = 0;
$json['message'] = "Error in registering. Probably the username/email already exists";
}
mysqli_close($this->db->getDb());
}
else{
$json['success'] = 0;
$json['message'] = "Error in registering. Email Address is not valid";
}
}
return $json;
}
public function loginUsers($email, $password){
$json = array();
$canUserLogin = $this->isLoginExist($email, $password);
if($canUserLogin){
$json['success'] = 1;
$json['message'] = "Successfully logged in";
}else{
$json['success'] = 0;
$json['message'] = "Incorrect details";
}
return $json;
}
}
?>
index.php
<?php
require_once 'user.php';
$username = "";
$password = "";
$email = "";
if(isset($_POST['email'] && isset($_POST['password']))){
$email = $_POST['email'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
$userObject = new User();
// Registration
if(!empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($email, $hashed_password);
echo json_encode($json_registration);
}
// Login
if(!empty($password) && empty($email)){
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($email, $hashed_password);
echo json_encode($json_array);
}
?>
I would recommend you to use a Password Entry instead of a visible entry in your app like a PasswordBox. Try to make your request like that.
var loginUrl = "http://localhost/test/index.php";
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{ { "username", emailbox.Text }, { "password", passwordbox.Text } };
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(loginUrl, content);
string result = await response.Content.ReadAsStringAsync();
}
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.
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.
so after hours on the web searching for smallest details or solution for this error I still can't fix it
The errors :
Notice: Undefined variable: Login in C:\xampp\htdocs\up\administration\adduser.php on line 3
Fatal error: Call to a member function AddUser() on a non-object in C:\xampp\htdocs\up\administration\adduser.php on line 3
These errors are from adduser.php which contains
<?php
require_once('LoginClass.php');
$Login->AddUser('Test','test312');
?>
And this is the LoginClass.php
<?php
class Login {
//Username Variables
private $username;
private $password;
//MySQL Variables
private $Host;
private $MySQLUsername;
private $MySQLPassword;
private $Database;
private $Conn;
//Constructor
public function Login()
{
session_start();
$this->Host = "localhost";
$this->MySQLUsername = "root";
$this->MySQLPassword = "";
$this->Database = "up";
$this->Connection();
unset($this->Host);
unset($this->MySQLUsername);
unset($this->MySQLPassword);
unset($this->Database);
}
//**********************
//Mysql Functions
//**********************
public function Connection()
{
$this->Conn = #mysql_connect($this->Host,$this->MySQLUsername,$this->MySQLPassword);
if($this->Conn)
{
mysql_select_db($this->Database) OR die('Could not select DB');
}
else
{
die(mysql_error());
}
}
public function Query($sql)
{
$result = mysql_query($sql);
if(!$result)
{
die(mysql_error());
}
return $result;
}
public function Disconnect()
{
mysql_close($this->Conn);
}
//Escapes bad values for MySQL to prevent SQL injections.
public function EscapeString($badstring)
{
if(!get_magic_quotes_gpc())
{
$goodstring = addslashes($badstring);
}
else
{
$goodstring = stripslashes($badstring);
}
$goodstring = mysql_real_escape_string($badstring);
return $goodstring;
}
public function EncryptPassword($password)
{
return sha1(md5($password));
}
//Check if the user can login
public function CheckLogin($username,$password)
{
$this->username = $this->EscapeString($username);
$this->password = $this->EscapeString($this->EncryptPassword(($password)));
$result = $this->Query("SELECT * FROM `users` WHERE `username` = '$this->username' AND `password` = '$this->password' LIMIT 1");
//If we get one result we know the login is right.
if(mysql_num_rows($result) == 1)
{
$this->username = $username;
$_SESSION['username'] = $this->username;
$_SESSION['authorized'] = 1;
header('location:Private.php');
}
else
{
die('Invalid Login');
}
}
//Add a user
public function AddUser($username,$password)
{
//$username = $this->EscapeString($username);
//$password = $this->EscapeString($this->EncryptPassword($password));
$username = $this->$username;
$password = $this->$this->EncryptPassword($password);
$result = $this->Query("INSERT INTO `users` (username,password) VALUES ('$username','$password')");
}
//Takes the result of a query and puts the information into an array
public function Result_To_Array($result)
{
$result_array = array();
for ($i=0; $row = mysql_fetch_array($result); $i++)
{
$result_array[$i] = $row;
}
return $result_array;
}
//Delete user
public function DeleteUser($username)
{
$username = $this->EscapeString($username);
$result = $this->Query("DELETE FROM `users` WHERE `username` = '$username' LIMIT 1");
}
//Checks if the user is authorized or not
public function IsAuth()
{
if(isset($_SESSION['username']) && $_SESSION['authorized'] == 1)
return true;
else
{
die('You are not authorized to view this information');
header('login.html');
}
}
//Shows user's IP
public function GetIP()
{
return $_SERVER['REMOTE_ADDR'];
}
//Display all users
public function ShowUsers()
{
$users = $this->Result_To_Array($this->Query("SELECT * FROM `users`"));
foreach($users as $user)
{
echo $user['username']."<br />";
}
}
public function LogOut()
{
session_destroy();
header('location:login.html');
}
}
?>
you should create new object Login() :
require_once('LoginClass.php');
$Login = new Login();
$Login->AddUser('Test','test312');
or call the function directly like this :
require_once('LoginClass.php');
Login::AddUser('Test','test312');
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.