Script logging in with whatever put in username and password field - php

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....:)

Related

destroying session if not set using php pdo

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();
}

how to make login for different user and type

im doing a system for school which by the user will be admin, teacher and parents.
im having problem to differentiate two user right now which is admin and parents.
i cant make sure that admin will directly go to admin.php and parent type will be on parent.php
any helps will be great! thanks in advance.
and the problem now is that the authentication for the user went wrong if the user enter a wrong username/password, they still can make it to the system.
<?php
session_start();
require("conection/connect.php");
$msg="";
if(isset($_POST['btn_log'])){
$uname=$_POST['unametxt'];
$pwd=$_POST['pwdtxt'];
$type=$_POST ['type'];
$sql=mysql_query("SELECT * FROM users_tbl
WHERE username='$uname' AND password='$pwd' AND type='$type'
");
$cout=mysql_num_rows($sql);
if (isset($type))
{
$_SESSION['Parent'] = $type;
header("location: parent.php");
}
else {
$_SESSION['Admin'] = $type;
header("location: admin.php");
exit;
}
}
?>
First don't use mysql_ it's deprecated.
I assume... $type = a means admin and p means oarent.
$sql=mysql_query("SELECT * FROM users_tbl WHERE username='$uname' AND password='$pwd'");
$count=mysql_num_rows($sql);
if($count>0)
{
if ($type=='p')
{
$_SESSION['Parent'] = $type;
header("location: parent.php");
}
elseif($type=='a') {
$_SESSION['Admin'] = $type;
header("location: admin.php");
exit;
}
}
else
{
echo "Wrong username or password";
}
here some solutions. You didn't check if the 'cout' was > 0 (mean found) !
mysql_ driver
Here a solution with your driver (mysql_) :
<?php
session_start();
require("conection/connect.php");
$msg = "";
if(isset($_POST['btn_log'])){
if(isset($_POST['unametxt'], $_POST['pwdtxt'], $_POST['type'])) {
$uname = mysql_real_escape_string($_POST['unametxt']);
$pwd = mysql_real_escape_string($_POST['pwdtxt']);
$type = mysql_real_escape_string($_POST['type']);
$sql = mysql_query("SELECT * FROM users_tbl WHERE username = '$uname' AND password = '$pwd' AND type = '$type'");
$cout = mysql_num_rows($sql);
if($cout > 0){
$_SESSION['type'] = $type;
if($type == "parent")
header("location: parent.php");
else if($type == "admin")
header("location: admin.php");
exit();
}
}
}
PDO version
The mysql_ driver is deprecated and you should use PDO instead. So I did the script for PDO driver too :
<?php
session_start();
require("connection/connect.php"); // PDO connection on $db variable
$db = connect();
// Function to connect an user
function login($db, $uname, $password){
$req = $db->prepare("SELECT * FROM users_tbl WHERE username = :username AND password = :password");
$req->bindParam("username", $uname, PDO::PARAM_STR);
$req->bindParam("password", $password, PDO::PARAM_STR);
$req->execute();
$user = $req->fetch();
if(isset($user['username'])){
$_SESSION['user'] = $user; //store all user datas (including type !)
return true;
}
return false; // fail connection
}
// logic to handle connection form
if(isset($_POST['btn_log'], $_POST['unametxt'], $_POST['pwdtxt'], $_POST['type'])){
if(login($db, $_POST['unametxt'], $_POST['pwdtxt'])){
if(isset($_SESSION['user']['type']) AND $_SESSION['user']['type'] == "admin")
header("location: admin.php");
else
header("location: parent.php");
exit();
}
else
echo "A problem occured !";
}
connect.php (pdo)
define("SQL_USER", "root"); // user
define("SQL_HOST", "localhost"); // host
define("SQL_PASS", ""); // password
define("SQL_DBNAME", ""); //db name
function connect(){
try {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$pdo_options[PDO::ATTR_DEFAULT_FETCH_MODE] = PDO::FETCH_ASSOC;
return new PDO('mysql:host='.SQL_HOST.'; dbname='.SQL_DBNAME, SQL_USER, SQL_PASS, $pdo_options);
}
catch (Exception $e){
die("Error connecting to database");
}
}

Cannot validate right? Why? New to PDO

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.

PHP get the email of a user currently logged in

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);
}

grab current user id - php class

I am buidling a small job application website, and i'm using a the basis of a login system taken from a Nettuts.com tutorial.
The logging in works fine, but I am having trouble getting the details for the currently logged in user, for example if a user enters their personal details, i can process the data into the database but it's not linked to which user!
I ideally want the id put into a variable called $userID.
I need a way to identify the user currently logged in, so i can update my insert statements to something like ...
'UPDATE cv where userID = $userID'.
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;
}
}
}
}
class Membership {
function validate_user($un, $pwd) {
$mysql = New Mysql();
$ensure_credentials = $mysql->verify_Username_and_Pass($un, md5($pwd));
// if above = true
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['username'] = $un;
$_SESSION['password'] = $pwd;
header("location: ../myIWC.php");
} else return "Please enter a correct username and password";
}
function log_User_Out() {
if(isset($_SESSION['status'])) {
unset($_SESSION['status']);
unset($_SESSION['username']);
unset($_SESSION['password']);
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");
}
$currentUN = $_SESSION['username'];
$currentPWD = $_SESSION['password'];
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('SELECT id FROM users WHERE username = ? AND password = ? LIMIT 1');
$stmt->bind_param('ss',$currentUN, $currentPWD);
$stmt->execute();
$stmt->bind_result($currentID);
}
Think of rewriting your verify_Username_and_Pass function so it return an array of user data, or writing a new function that gets it.
Then in your validate_user function, save this data to session:
$_SESSION['user_data'] = $user_data; // got from database
Well I would say the code given in the tutorial isn't a very good example. The database class should be just that and only handle database functions it shouldn't really have user functions in there (verify_Username_and_Pass). Also from a security point of view I would strongly recommend against storing unencrypted passwords in the session.
I appreciate however the code snippets you've provided are probably part of a wider implementation and as such you won't be able to play around with it too much. As such the code below will work in your context.
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 id
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($id);
if($stmt->fetch()) {
$stmt->close();
return $id;
} else {
return false;
}
}
}
Then in your user class
if($ensure_credentials !== false) {
$_SESSION['id'] = $ensure_credentials;
$_SESSION['status'] = 'authorized';
$_SESSION['username'] = $un;
$_SESSION['password'] = $pwd;
header("location: ../myIWC.php");
} else return "Please enter a correct username and password";

Categories