I want to get a 'INT' value from a DB::Select get() - php

I want to make a simple login and redirect each user to their private page, so each user will have their own page. Like www.example.com/user1.
This is for my new Application that I'm developing in this job.
public function login(request $req){
$username = $req->input('username');
$password = $req->input('password');
$type = 1;
$checklogin = DB::table('users')->where(['username'=>$username,'password'=>$password])->get();
$checktype = DB::table('users')->where(['username'=>$username,'password'=>$password,'type'=>$type])->get();
$url2 = DB::table('users')->where(['username'=>$username,'password'=>$password])->get('id');
if(count($checklogin) >0){
if (count($checktype) ==1) {
header("Location: /admin/$url2", true, 301);
exit();
}else{
if ($url2 == 4) {
echo "$url2";
}
}
}else{
return view('loginfailed');
}
}
}
The url that is redirecting is: "http://localhost:8000/admin/[%7B%22id%22:2%7D]"

You can fetch id as,
// fetching 1 record and then id of it
$url2 = DB::table('users')->where(['username'=>$username,'password'=>$password])->first()->id;

public function login(request $req){
$username = $req->input('username');
$password = $req->input('password');
$checklogin = DB::table('users')->select('type')->where(['username'=>$username,'password'=>$password])->get()->first();
if(count($checklogin){
if ($checklogin->type ==1) {
header("Location: /admin/$url2", true, 301);
exit();
}elseif ($checklogin->type == 4) {
//do something else
}
}else{
return view('loginfailed');
}
}
}

Related

Password Hash and in Codeigniter

I can hash the password during user registration,but comparing them from the user input during login with the one in the database isn't working.getting errors.
This is the insert for registration.Kindly show me where i'm going wrong
public function insert_client($codeDigits)
{
$options = ['cost'=>12];
$response = $this->taken_email($_POST['Email']);
if($response){
$returned = false;
}else{
$this->FirstName = $_POST['FirstName'];
$this->LastName = $_POST['LastName'];
$this->Email = $_POST['Email'];
$this->Role_Id = 2;
$this->Password = password_hash($_POST['Password'],PASSWORD_BCRYPT,$options);
$this->PhoneNo = $_POST['PhoneNo'];
$this->confirmCode = $codeDigits;
$this->db->insert('users', $this);
$returned = true;
}
return $returned;
}
This is the login model,the query for login
public function login_model2($email,$password)
{
$options = ['cost'=>12];
$this->db->select('*');
$this->db->from('users');
$this->db->where('Email',$email);
//$this->db->where('Password',$password);
$this->db->where('Role_Id !=',1);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$data = $query->row();
// storing the results in the variable $data
if(password_verify($password,$data->password))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
This is the login controller function when logging in
public function post_login2()
{
$this->form_validation->set_rules('Email', 'Email', 'trim|required|min_length[6]');
$this->form_validation->set_rules('Password', 'Password', 'trim|required|min_length[6]');
if($this->form_validation->run() == TRUE ){
if($this->Users_model->login_model2($_POST['Email'],$_POST['Password']))
{
//test for redirect
if ($_SESSION['role'] == 2) {
redirect("Client/welcome");
} else if ($_SESSION['role'] == 3) {
redirect("Pro/welcome");
}
// test for redirect
}else{
//
$this->session->set_flashdata('err', true);
redirect("Welcome/login");
}
}else{
$this->login();
}
}
Simply change $data->password to $data->Password
In model login_model2(), password_verify should be like this :
if(password_verify($password,$data->Password))
{
return true;
}
else
{
return false;
}

pull from session user info

ok I have a user login that uses email address and password when they login I want to pull there session data
like username and anything else from there record
I use this
<?php
if(isset($_SESSION['email'])) {
echo $_SESSION['email'];
}
?>
it works and pulls there email address but how do I get there username? I tried changing email to username and nothing shows
my login setup
/* login functions */
function login_user($email, $password, $remember)
{
$sql = "SELECT user_pwd, uid FROM users WHERE user_email = '" . escape($email) . "' AND active = 1";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['user_pwd'];
if (password_verify($password, $db_password)) {
if ($remember == "on") {
setcookie("email", $email, time() + 86400,'/');
}
$_SESSION['email'] = $email;
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
/* User Logged in Function */
function logged_in(){
if (isset($_SESSION['email']) || isset($_COOKIE['email'])) {
return true;
} else {
return false;
}
}
You need to make small changes in login_user() function.
function login_user($email, $password, $remember)
{
$sql = "SELECT user_pwd, uid, username FROM users WHERE user_email = '" . escape($email) . "' AND active = 1";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['user_pwd'];
if (password_verify($password, $db_password)) {
if ($remember == "on") {
setcookie("email", $email, time() + 86400,'/');
}
$_SESSION['email'] = $email;
$_SESSION['username'] = $row['username'];
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
Now you can use below code to get username in session. But make sure you must have username field in users table.
if(isset($_SESSION['username'])) {
echo $_SESSION['username'];
}

Login code works on localhost but doesn't work on Godaddy Server

I developed a small project. which was working fine in localhost. After hosting, it I set up a database and now login doesn't work. Here is my code.
This is the script Iam using near admin form.
$(document).ready(function(){
$('#login_form_button').click(function(event){
event.preventDefault();
$('#fill_form').css('display','none');
$('#correct_form').css('display','none');
var username = $('#email').val();
var password = $('#pwd').val();
if(username == '' || password == ''){
$('#fill_form').css('display','block');
}else{
$.post('admin_login.php', {check:'check'}, function(data){
if(data == '1'){
window.location.href= 'admin_home.php';
}else{
$.post('admin_login.php', {username:username, password:password}, function(data){
if(data == '1'){
window.location.href= 'admin_home.php';
}else{
alert(data); $('#correct_form').css('display','block');
}
});
}
});
}
});
});
</script>
This is admin_login.php
<?php
require_once 'php/core/init.php';
if(Input::exists()){
$input_string = Input::get('check');
if($input_string === 'check'){ if(Session::exists(Config::get('session/admin_name'))){
echo '1';
exit();
}
}
$username = Input::get('username');
$password = Input::get('password');
$user = new User();
$username = User::sanitize($username);
$password = User::sanitize($password);
if($user->login_admin($username, $password)){
echo '1';
}else{
echo 'none m';
}
}
This is User.php
<?php
class User{
private $_db;
public function __construct($user = null){
$this->_db = DB::getInstance();
}
public function create($fields){
if(!$this->_db->insert('users', $fields)){
throw new Exception('Problem creating an account');
}
}
public function login($username = '', $password = ''){
$db_obj = $this->_db->query("SELECT * FROM users WHERE email = ? AND password = ?", $fields = array(
$username,
$password
));
if($db_obj->count()==1 && !$db_obj->error()){
$got_pass = $db_obj->first();
$gotpass = $got_pass["password"];
$id = $got_pass["id"];
if($gotpass === $password){
Session::put(Config::get("session/session_id"), $id); Session::put(Config::get("session/session_name"), $username);
return true;
}
else{
return false;
}
}
else{
return false;
}
}
public function login_admin($username = '', $password = ''){
$db_obj = $this->_db->query("SELECT * FROM admin WHERE username = ? AND password = ?", $fields = array(
$username,
$password
));
if($db_obj->count()==1 && !$db_obj->error()){
$got_pass = $db_obj->first();
$gotpass = $got_pass["password"];
$id = $got_pass["id"];
if($gotpass === $password){
Session::put(Config::get("session/admin_id"), $id); Session::put(Config::get("session/admin_name"), $username);
return true;
}
else{
return false;
}
}
else{
return false;
}
}
public static function sanitize($string){
return mysql_real_escape_string(strip_tags($string));
}
public static function logout(){
Session::delete(Config::get('session/admin_name'));
Session::delete(Config::get('session/admin_id'));
Session::delete(Config::get('session/session_name'));
Session::delete(Config::get('session/session_id'));
Redirect::to("index.php");
}
}
I cross checked PDO Connection It works fine when I run test.php
test.php
<?php
require_once 'php/core/init.php';
$db = DB::getInstance();
$inst = $db->get('users', array('1','=', '1'));
$results = $inst->results();
foreach($results as $result){
print_r($result);
}
?>
$user->admin($username, $password) is always returning false in admin_login.php
Any help would be really appreciable. Thank you.

PHP Login Script Broken

Hello Ladies and Gentlemen, I have been working on this project for some time now. And all of a sudden when I go into the web page to login I just get a blank screen at the 'success_login.php' which is literally just the login script that runs once login is clicked on my screen.
Here is the success_login.php script:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/luke/classes/userFunctions.php');
$userFunctions = new userFunctions();
session_start();
//assign all posted values to a session
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
$_SESSION['login_info'][$key] = $value;
}
}
//Get the username and password
$username = htmlentities($_POST["username"], ENT_QUOTES);
$password = htmlentities($_POST["password"], ENT_QUOTES);
//Get the user id if the login was valid
$userId = $userFunctions->validLogin($username,$password);
if($userId != 0) {
$_SESSION['login_info']['username'] = $username;
$_SESSION['login_info']['password'] = $password;
$_SESSION['login_info']['user_id'] = $userId;
header('LOCATION: home.php');
exit;
}
header('LOCATION: login.php');
exit;
?>
and here is the function it refers to:
public function validLogin($username,$password) {
$dbact = new DbInteraction();
$query = "select * from person";
$result = $dbact->interact($query,true);
$row = mysql_numrows($result);
$valid = false;
$userId = 0;
while ($row = mysql_fetch_array($result)) {
//Check to see if the username and password are valid
$validUsername = strcmp($username,$row['username']);
if($validUsername == 0) {
$hashedPassword = md5($password . Constants::SALTED);
$validPassword = strcmp($hashedPassword,$row['password']);
if($validPassword == 0) {
$valid = true;
$userId = $row['idperson'];
}
}
}
if(!$valid) {
$_SESSION['login_info']['username'] = "error";
$_SESSION['login_info']['password'] = "";
header('LOCATION: login.php');
exit;
return $userId;
} else {
$_SESSION['login_info']['username'] = "";
$_SESSION['login_info']['password'] = "";
return $userId;
}
}
Like I said, its been working for months and now all of a sudden its not anymore, and it has me really worried. Could someone shed some light for me?
Thanks a million for your time!

Session is not being stored

Would anyone please show me how to solve this problem? I spent many days looking for the solution, but I couldn't find one.
Here's my problem.
"login.php" file:
require_once("./include/membersite_config.php");
if(isset ($_POST['submitted']))
{
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("login-home.php");
}
}
**membersite_config . php ** contains host, username, pass, and also calls **fg_membersite . php ** which contains functions:
function Login()
{
if(empty($_POST['username']))
{
$this->HandleError("UserName is empty!");
return false;
}
if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if(!isset($_SESSION))
{
$sessid = session_start();
}
if(!$this->CheckLoginInDB($username, $password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $username;
** echo empty($_SESSION[$sessionvar])? 'true' : 'false'; **
return true;
}
function CheckLogin()
{
if(!isset($_SESSION))
{
session_start();
}
$sessionvar = $this->GetLoginSessionVar();
** echo empty($_SESSION[$sessionvar])? 'true' : 'false'; **
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
function GetLoginSessionVar()
{
$retvar = $this->rand_key;
$retvar = 'usr_' . substr($retvar, 0);
return $retvar;
}
function CheckLoginInDB($username, $password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$username = $this->SanitizeForSQL($username);
$pwdmd5 = $password;
$qry = "Select name, email from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";
$result = mysql_query($qry, $this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error logging in. The username or password does not match");
return false;
}
$row = mysql_fetch_assoc($result);
$_SESSION['name_of_user'] = $row['name'];
$_SESSION['email_of_user'] = $row['email'];
return true;
}
**login - home . php ** after successfully logged in:
require_once("./include/membersite_config.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
Th problem is: I already echoed to check the status of the $_SESSION[] array. After I input the correct username and password, the echo empty($_SESSION[$sessionvar]) ? 'true': 'false'; in Login function shows false, but the one in CheckLogin shows true. I dont know why.
session_start() starts or continues the session by adding cookies or a query parameter to identify the user. You have to place it at the very top of your template (before anything is printed out, even a blank line), even if the user already has a session:
<?php
session_start();
?>

Categories