i have a simple login system and i get nothing when trying to fetch the number of rows, the same method used to work all the time, i dont know what is going on today.
Code:
<?php
class LoginClass {
public $User;
public $Pass;
public $Query;
function Init() {
$User = $this->User;
$Pass = $this->Pass;
if($User != '')
{
if($Pass != '')
{
$this->HashPass();
}
else
{
echo 'Please Enter A Password.';
}
}
else
{
echo 'Please Enter A Username or E-Mail.';
}
}
function HashPass() {
$Pass = $this->Pass;
$this->Pass = hash('sha256', $Pass);
$this->CheckUser();
}
function CheckUser() {
$User = $this->User;
if(!filter_var($User, FILTER_VALIDATE_EMAIL))
{
$this->Query = 'SELECT * FROM Users WHERE User = "'.$User.'" AND Pass = "'.$this->Pass.'"';
}
else
{
$this->Query = 'SELECT * FROM Users WHERE EMail = "'.$User.'" AND Pass = "'.$this->Pass.'"';
}
$this->CheckDB();
}
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->prepare($Query)
$Stmt->execute();
$Stmt->store_result();
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
function SetupSession() {
echo 'Test';
}
}
the Check DB is the problem here and im able to echo out the query variable in that function everything is fine, here is exactly what i get
SELECT * FROM Users WHERE User = "Test" AND Pass = "532eaabd9574880dbf76b9b8cc00832c20a6ec113d682299550d7a6e0f345e25"
I also checked my DB and all my tables are setup correctly and there is no password.
OK, need more space than the comments area, the issue is clearly in this block:
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->prepare($Query)
$Stmt->execute();
$Stmt->store_result();
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
I think it's because you aren't binding parameters to the prepared statement, you've already included them inline in your earlier statement. Therefore, you probably want to:
Switch to non-prepared statement
The easy option here will be to switch to a non-prepared statement. Replace your block with:
function CheckDB() {
$Query = $this->Query;
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Stmt = $Connect->query($Query)
echo $Stmt->num_rows;
$Stmt->close();
$Connect->close();
}
A word of caution with this approach: you need to sanitize your user input in the block which defines $User, otherwise you're leaving yourself open to mysql injection. In that block, change this line:
$User = $this->User;
To the following:
$User = mysql_real_escape_string($this->User);
Related
I am experiencing a problem where I can't use the parameter in the function in other functions more specifically the $studentnumber parameter, is it possible for the parameters used in other functions, the parameter used were dynamic parameter. I'm new to PHP so my terminology might be off I the end goal is to make $studentnumber, able to be used in other functions.
public function login($studentnumber, $password) {
$conn = dbconnection();
$stmt = $conn->prepare("SELECT * FROM login WHERE studentnumber = :studentnumber");
$stmt->bindParam(':studentnumber', $studentnumber);
$stmt->execute();
$row = $stmt->fetch();
if ($password == $row['password']) {
echo $studentnumber;
return true;
} else {
return false;
}
}
public function login($studentnumber, $password) {
$this->studentnumber = $studentnumber;
$conn = dbconnection();
$stmt = $conn->prepare("SELECT * FROM login WHERE studentnumber = :studentnumber");
$stmt->bindParam(':studentnumber', $studentnumber);
$stmt->execute();
$row = $stmt->fetch();
if ($password == $row['password']) {
echo $this->studentnumber;
return true;
} else {
return false;
}
}
Sorry, but once again I return with a long post for those that can spend a little of their time helping out a troubled noob.
I've been having some difficulties and asked here previously for any guidance on how to draw any users first and last name from the database, when only given the username and password at login.
When my code was edited now it seems anyone can login with whatever they desire.
Login.php script as follows:
<?php
session_start();
require_once 'classes/membership.php';
$membership = new Membership();
// If the user clicks the "Log Out" link on the index page.
if(isset($_GET['status']) && $_GET['status'] == 'loggedout') {
$membership->log_User_Out();
}
// Did the user enter a password/username and click submit?
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
?>
This points to Membership.php first:
<?php
require 'mysql.php';
class Membership {
function validate_user($un, $pwd) {
$mysql = New Mysql();
$ensure_credentials = $mysql->verify_Username_and_Pass($un, md5($pwd));
list($ensureCredentials, $data) = $mysql->verify_Username_and_Pass($un, md5($pwd));
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['fname'] = $data['fname'];
$_SESSION['lname'] = $data['lname'];
header("location: medlem.php");
} else return "Please enter correct username and password";
}
function log_User_Out() {
if(isset($_SESSION['status'])) {
unset($_SESSION['status']);
if(isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time() - 1000);
session_destroy();
}
}
function confirm_Member() {
session_start();
if($_SESSION['status'] !='authorized') header("location: login.php");
}
}
Which then again points forward to mysql.php:
<?php
require_once 'includes/constants.php';
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
// UPDATE : I added correct usage of the stmt here.
$result = $stmt->get_result();
if($row = $result->fetch_array()) {
$stmt->free_result();
$stmt->close();
// returning an array the first item is the validation the second is the data.
return array(true, $row);
}
}
// if there is no just return empty data, and false for validation.
return array(false, array());
}
}
For the sake of re-usability I've used constants for this project:
<?php
// Define constants here
define('DB_SERVER', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_NAME', 'sameige_membership');
With this current script set, it will login with whatever I set in the username and password field. The webpages are also supposed to post first and lastname to tell the user who and if he is logged in posted by $_SESSION('fname/lname').
The login works as it's supposed to when I revert to what I had in the beginning. Before adding to query part for drawing first and lastname from DB.
Here is the original one:
<?php
require_once 'includes/constants.php';
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
return true;
}
}
}
}
To my understanding this scirpt should compare $_POST['username']/['password'] to the selected username and password fields in the database. And if they are correct it should comeback with a login and redirect to the medlem.php page. If else it should return to enter correct username and password.
This however logs in and redirect nonetheless.
Any answer to what I am doing worng would be greatly appriciated, as I am a total noob on the subject.
Regards, Josh
First of all your code about checking the user input is wrong... You should check if isset($_POST['username'] && isset($_POST['password']) and not if($_POST) like you do.
Second you say : $response = $membership->validate_User($_POST['username'], $_POST['pwd']); and your class is : validate_user.... It's case sensitive (use Dreamweaver if you can, it warns you about mistakes like these)
3rd solve them and check again.
<?php
session_start();
require_once 'classes/membership.php';
$membership = new Membership();
// If the user clicks the "Log Out" link on the index page.
if(isset($_GET['status']) && $_GET['status'] == 'loggedout') {
$membership->log_User_Out();
}
// Did the user enter a password/username and click submit?
Use isset($_POST['submit']) in place of just $_POST and note methods are case sensitive. So it would be validate_user not validate_User
if(isset($_POST['submit']) && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_user($_POST['username'], $_POST['pwd']);
}
?>
Now in your mysql.php, I would do it like this:
<?php
require_once 'includes/constants.php';
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
// UPDATE : I added correct usage of the stmt here.
$result = $stmt->get_result();
if($row = $result->fetch_assoc()) {
$stmt->free_result();
$stmt->close();
// returning an array the first item is the validation the second is the data.
$result['data']=$row;
$result['validation']=true;
return $result;
}
}
// if there is no just return empty data, and false for validation.
$result['data']=array();
$result['validation']=false;
return $result;
}
}
Now I will have the following changes in Membership.php
function validate_user($un, $pwd) {
$mysql = New Mysql();
$ensure_credentials = $mysql->verify_Username_and_Pass($un, md5($pwd));
$data=$ensure_credentials['data'];
$validation=$ensure_credentials['validation'];
if($validation) {
$_SESSION['status'] = 'authorized';
$_SESSION['fname'] = $data['fname'];
$_SESSION['lname'] = $data['lname'];
header("location: medlem.php");
} else return "Please enter correct username and password";
Hope this works for you....:)
I have a problem. I want to get the email of a user, the email is a special column in a table called users in my database. I created a login-system that is working well, but I still want to get the e-mail of the user who is currently logged in.
I am really new to php and mysql. :(
This is my code in login.php:
<?php
require 'Mysql.php';
class Membership {
//Check if input is correct
function validate_user($un, $pwd) {
$mysql = New Mysql();
$ensure_credentials = $mysql->verify_Username_and_Pass($un, $pwd);
//input correct
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION["username"] = $un;
$_SESSION["email"] = $ensure_credentials['email'];
header("location: ?status=authorized");
}
function log_User_Out() {
if(isset($_SESSION['status'])) {
unset($_SESSION['status']);
if(isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time() - 10000);
session_destroy();
}
if(isset($_SESSION["username"])) {
unset($_SESSION["username"]);
}
if(isset($_SESSION["email"])) {
unset($_SESSION["email"]);
}
}
}
and here from Mysql.php:
<?php
require "/data/logindata/constants.php";
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
$stmt->bind_result($username, $email); // the columns fetched with SELECT *
if (!$stmt->fetch()) {
return false;
}
return array(
'username' => $username,
'email' => $email
);
}
return false;
}
}
Instead of returning a boolean, you may return some user data with verify_Username_and_Pass function. There you can include authenticated user's email:
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT username, password
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
$stmt->bind_result($username, $email); // the columns fetched with SELECT *
if (!$stmt->fetch()) {
return false;
}
return array(
'username' => $username,
'email' => $email
);
}
return false;
}
....
$ensure_credentials = $mysql->verify_Username_and_Pass($un, $pwd);
//input correct
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION["username"] = $un;
$_SESSION["email"] = $ensure_credentials['email'];
header("location: ?status=authorized");
}
First of all be sure to sanitize every variable inserted by final users.
It's very important to sanitize your variable to avoid SQL injection.
Then on the Session variable user I'm gonna save the user Id and to get his/her email I'm gonna make a function that should receive the session id to return an email.
Now I'm gonna write a couple of functions that could be useful:
function logged() {
return (isset($_SESSION['id_user'])) ? true : false;
}
function getEmail($userId) {
$userId = sanitize(userId);
$query = "SELECT userEmail FROM users WHERE id_user =" . $userId;
$name = mysql_result(mysql_query($query), 0);
return $name;
}
function sanitize($data) {
return mysql_real_escape_string($data);
}
I'm learning php and OOP programming here. I have below working code I am trying to modify to prevent sql injection. Other people showed me the idea of how to use PDO. But I'm having difficulty getting it to work.
Basically this function is to pass the $uid and $password to check the user.
What am I doing wrong?
user_function.php
<?php
class DB_Functions {
private $db;
function __construct() {
require_once 'db_connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
public function getUser($uid, $password) {
$result = mysql_query("SELECT * FROM users WHERE id = '$uid' AND pswd = '$password'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
return false;
}
}
}
?>
modified code
<?php
class DB_Functions {
private $db;
function __construct() {
require_once 'db_connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
public function getUser($uid, $password) {
$stmt = $db->prepare("SELECT * FROM users WHERE id=? AND pswd=?");
$stmt->execute(array($uid, $password));
return $stmt->fetch();
}
}
?>
check for user (index.php)
require_once 'include/db_functions.php';
$db = new DB_Functions();
if ($tag == 'login') {
$uid =mysql_real_escape_string($_POST['id']);
$password =mysql_real_escape_string($_POST['pswd']);
// check for user
$user = $db->getUser($uid, $password);
if ($user != false) {
$response["success"] = 1;
$response["user"]["id"] = $user["id"];
echo json_encode($response);
} else {
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
You're missing the point entirely of PDO. With properly prepared queries using placeholderse, you do not have to do ANY escaping yourself.
As well, mysql_real_escape_string() depends on there being an active database connection established with mysql_connect(). Without that, your m_r_e_s() will not work and will return a boolean false for "failed". You then try to use those false values in your query.
DB connections established by PDO are not shareable with mysql_(), mysqli_(), etc... Each of those libraries mantains their own independent connection pool.
You're using PDO, so you can't use mysql_real_escape_string(). You don't need to escape the parameters, as PDO will automatically escape them for you in your prepared query.
So, just call getUser() like this:
if ($tag == 'login') {
// check for user
$user = $db->getUser( $_POST['id'], $_POST['pswd']);
... etc
I have this code, and works perfectly, but i want to make a simple modification
<?php session_start();
require 'includes/f_banco1.php';
require '../PasswordHash.php';
function checkBd($sql, $db, $user, $codePass) {
$user = $_GET['userid']; //here
$codePass = $_GET['code'];//here
if(is_numeric($user)) {
($sql = $db->prepare("select userid, code from password_reset where userid=? and code=?"));
$sql->bind_param('ss', $user, $codePass);
$sql->execute();
$sql->bind_result($user, $codePass);
if ($sql->fetch()) {
$_SESSION['u_name']= sha1($user);
header("location: updatePass.php");
return true;
}
else
echo "Não existe na BD";
return false;
}
else
echo "Erro";
}
checkBd ($sql, $db, $user, $codePass);
?>
i want to change these lines
$user = $_GET['userid']; //here
$codePass = $_GET['code'];//here
to
$user = mysqli_real_escape_string($db, $_GET['userid']);
$codePass = mysqli_real_escape_string($db, $_GET['code']);
but with this change the code simple stops work, an echo of $user doesn't show nothing
any idea?
thanks
You do not need to do that. You are using prepared statements, which escape the variables automatically.
If you prepare your statement, you don't need to escape your string.
Note: Your database connection must be opened to use mysqli_real_escape_string()