0

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

}
Bluedayz
  • 599
  • 5
  • 17

2 Answers2

5

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");
} 
A.Essam
  • 1,094
  • 8
  • 15
mesutozer
  • 2,839
  • 1
  • 12
  • 13
  • 1
    Exactly, although to keep the code's intention clear, and improve separation of concerns, I would split it into 2 functions: `fetchUserData()` to run the query, and `verifyUsernameAndPass()` which checks the result. – lethal-guitar Mar 29 '14 at 17:00
  • Somehow, it doesnt work. I think I need to add "AND email = ?" in $query, do I? – Bluedayz Mar 29 '14 at 17:02
  • @user3389375 no, that would mean checking for a certain email. You already have `select *`, so the email should be included. – lethal-guitar Mar 29 '14 at 17:03
  • Try `print_r()` on the result of `$stmt->fetch()` – lethal-guitar Mar 29 '14 at 17:04
  • I had a space character in `$_SESSION["email"] = $ensure_credentials['email'];` row between `$ensure_credentials` and `['email']`. That might be the problem. now fixed my answer – mesutozer Mar 29 '14 at 17:06
  • ok, what does print_r() mean and where does it have to be exactly? the space wasn't the problem. – Bluedayz Mar 29 '14 at 17:06
  • could you give more information about the error? do you get empty resultset? any error message? – mesutozer Mar 29 '14 at 17:07
  • no, there is no error message, but normally the $_SESSION["email"] should be written to the website, but it doesnt. – Bluedayz Mar 29 '14 at 17:08
  • @lethal-guitar suggested to print_r `$stmt->fetch()` result. So, instead of directly returning `$stmt->fetch()`, you can print_r that. There you can confirm if email was fetched correctly – mesutozer Mar 29 '14 at 17:10
  • and where does print_r have to be written? – Bluedayz Mar 29 '14 at 17:14
  • Replace `return $stmt->fetch();` with `print_r($stmt->fetch()); exit;`. In fact I need to ask one thing first: For this code to work, you need to logout and login again after implementing this change. Did you do that? – mesutozer Mar 29 '14 at 17:18
  • yes of course and i reloaded the page a couple of times. – Bluedayz Mar 29 '14 at 17:21
  • wait, i have to write something that deletes the $_SESSION["email"] after loggedout! – Bluedayz Mar 29 '14 at 17:24
  • you need to completely destroy the session on logout – mesutozer Mar 29 '14 at 17:26
  • i update the question with the code for the log_user_out function – Bluedayz Mar 29 '14 at 17:30
  • ok, i have included the print_r and i get redirected to a page that is empty except for a "1". what does that mean? – Bluedayz Mar 29 '14 at 17:34
  • for logout: http://stackoverflow.com/questions/3512507/proper-way-to-logout-from-a-session-in-php for print_r: please view page source – mesutozer Mar 29 '14 at 17:39
  • Have a look at [the PHP manual](http://www.php.net/manual/en/mysqli-stmt.get-result.php), there's an example on getting data. The `1` you see is the return value of `$stmt->fetch()` - my bad, I mixed it up with `get_result()` (described on the page I linked) – lethal-guitar Mar 29 '14 at 17:45
  • thanks for the logout thing, I've also added in the index.php file, but there isnt anything. i try to login as a different user... | edit: it doesnt work here aswell, $_SESSION["email"] isn't defined correctly i think. – Bluedayz Mar 29 '14 at 17:58
  • Sorry, I just realized that I missed one thing. http://www.php.net/manual/en/mysqli-stmt.fetch.php now editing my answer – mesutozer Mar 29 '14 at 18:00
  • I just edited my answer to bind results to variables and return – mesutozer Mar 29 '14 at 18:04
  • syntax error in this line: "return return array(". only one time return? – Bluedayz Mar 29 '14 at 18:12
  • $stmt->bind_result($username, $email); // the columns fetched with SELECT * to this line, there is this error: "Number of bind variables doesn't match number of fields in prepared statement" – Bluedayz Mar 29 '14 at 18:18
  • you should either fetch only username & email, or bind all columns – mesutozer Mar 29 '14 at 18:21
  • so how do i fix that? – Bluedayz Mar 29 '14 at 18:25
  • by the way, $stmt->bind_result($un, $email); shouldn't that be correct instead of $username? 'username' => $un as well? – Bluedayz Mar 29 '14 at 18:34
  • Change your query to : `SELECT username, email FROM users ...`. – A.Essam Mar 29 '14 at 18:39
  • what about `SELECT username, password, email FROM users ...` – Bluedayz Mar 29 '14 at 18:44
  • You only need the username and the email from the database, you provide the password to check if it exists but you don't need it back. – A.Essam Mar 29 '14 at 18:50
  • ok i will try to write it like you did. so SELECT username, email FROM users WHERE username = ? AND password = ? LIMIT 1"; – Bluedayz Mar 29 '14 at 18:55
  • `SELECT username, email FROM users WHERE username = ? AND password = ? LIMIT 1`. Tell me what errors you get. – A.Essam Mar 29 '14 at 18:59
-2

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);
}
prelite
  • 1,073
  • 2
  • 9
  • 20
  • He's already using prepared statements, which is preferable to manually sanitizing. Also, `mysql_real_escape_string` is a different API, which is deprecated. He's already using `mysqli`. – lethal-guitar Mar 29 '14 at 17:07
  • On top of that: No need to run two separate queries. Run one query to check password, and fetch user data (including email) in one go. Minimize DB interaction to increase scalability. – lethal-guitar Mar 29 '14 at 17:09