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();
}
Related
where should I declare my session, then how to call my variable session, I need it to show user data. Correct if my question is wrong
this is login.php for my condition
session_start();
$_SESSION["Username"]="$Username";
require_once '../include/DBOperations.php';
$response=array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_POST['Username']) && isset($_POST['Password'])){
$db=new DBOperations();
if($db->login($_POST['Username'],$_POST['Password'])){
$response['error'] = false;
$response['Auth'] = "Success";
} else {
$response['error']=true;
$response['Auth'] = "Failed";
$response['message']="invalid Username or Password";
}
} else{
$response['error']=true;
$response['Auth'] = "Invalid";
$response['message']="Required fields are missing";
}
}
echo json_encode($response);
?>
this is DBOperations.php
function login($Username,$Password){
$anotherConnection = mysqli_connect("localhost","root","","sisro1");
$sql = "SELECT * FROM Pengguna WHERE Username='$Username' AND Password='$Password'";
$result = mysqli_query($anotherConnection,$sql);
$row = mysqli_num_rows($result);
if ($row == 1){
return true;
} else {
echo(mysqli_error($anotherConnection));
return false;
}
}
this isDBConnect.php for my connection
function connect(){
include_once dirname(__FILE__).'/Constrants.php';
//$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$dbName = "sisro1";
$dbHost = "Localhost";
$user = "root";
$pass = "";
$con = new PDO("mysql:host=$dbHost;dbname=$dbName", $user, $pass);
if(mysqli_connect_errno()){
echo "Failed to connect with database".mysqli_connect_err();
}
return $this->con;
}
you should start you session in the if condition of you login function
if ($row == 1){
$_SESSION["Username"]=$Username;
return true;
} else {
echo(mysqli_error($anotherConnection));
return false;
}
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....:)
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");
}
}
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.