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);
}
Related
My login form is always saying that credentials are incorrect. The form was working before I changed it to use either username or email. Not sure whats wrong with my code.
/****************User login functions ********************/
function login_user($email, $username, $password, $remember) {
$sql = "SELECT password, id FROM users WHERE email = '".escape($email)." || username = ".escape($username)."' AND active = 1";
$result = query($sql);
if(row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['password'];
if(md5($password) === $db_password) {
if($remember == "on") {
setcookie('email', $email, time() + 86400);
}
$_SESSION['email'] = $email;
$_SESSION['username'] = $username;
return true;
} else {
return false;
}
return true;
} else {
return false;
}
} // end of function
/****************logged in function ********************/
function logged_in(){
if(isset($_SESSION['email']) || isset($_COOKIE['email'])){
return true;
} else {
return false;
}
}
Im not sure if anyone can help me sort this out
I should add 2 single quotes in your SELECT
function login_user($email, $username, $password, $remember) {
$sql = "SELECT password, id FROM users WHERE email = '".escape($email)."'
|| username = '".escape($username)."' AND active = 1";
How can I fix the following code?
function userExists($pdow, $login)
{
$userQuery = "SELECT * FROM login u WHERE login=:user;";
$stmt = $pdow->prepare($userQuery);
$stmt->execute(array(':user' => $login));
return !!$stmt->fetch(PDO::FETCH_ASSOC);
}
$login = 'user';
$exists = userExists($pdow, $login);
if('$login')
$user= var_dump((bool) 'Exists');
{
echo "Login exsists!";
}
I have two problems with my code.
First error:
Error with echoing 'login exsists!'. I see this echo all the time in browser.
Second error:
When I get echo 'login exsists!' my code still inserts data to database.
Simply:
$servername = '';
$dbname = '';
$username = '';
$password = '';
$dbh = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password);
function user_exists($dbh, $Login) {
$Q = $dbh->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':Login', $Login);
$Q->execute();
return $Q->fetch(PDO::FETCH_ASSOC);
}
//Lets try:
$user = user_exists($dbh, 'email#example.com');
if ($user) {
echo 'User: ' . $user['login'] . ' was found in the database.';
} else {
echo 'The user was NOT found.';
}
if($login)
// this line doesnt make any sense!
// $user= var_dump((bool) 'Exists');
// so this is not a valid if clause
{
echo "Login exsists!";
}`
try {
$pdow = new PDO('mysql:host=localhost;dbname=log_cdr', 'root', 'slawek132');
$pdow -> query ('SET NAMES utf8');
$pdow -> query ('SET CHARACTER_SET utf8_unicode_ci');
$pdow->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlw = "INSERT INTO login (login, pass, pass_v, email, email_v)
VALUES ('".$_POST["login"]."','".$_POST["pass"]."','".$_POST["pass_v"]."','".$_POST["email"]."','".$_POST["email_v"]."')";
function user_exists($login) {
$Q = pdow()->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':login', $Login);
$Q->execute();
if ($Q->rowCount() != 0) {
//User exist:
return $Q->fetch(PDO::FETCH_ASSOC);
} else {
//User doesn't exist.
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 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.
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";