Learning php - How to query the database from logged_in.php? - php

Im trying to learn php and have set up a login system using php-login.net (advanced script). The script uses an index.php file to check if the user is logged in (via login.php)
Within login.php, the script uses a function "databaseConnection" to connect to the database as
$this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
An example query is executed as:
$query = $this->db_connection->prepare('UPDATE users SET username = :user_name WHERE user_id = 1');
$query ->bindValue(':user_name ', $user_name , PDO::PARAM_STR);
$query ->execute();
if ($query_update->rowCount() == 0) {
// Something here
} else {
// Something else here
}
index.php checks if the user is logged in and if logged in, loads logged_in.php
My question is: How do I select something from the database within logged_in.php. Should i create a new db connection? If so how. I cannot reference $this->db_connection->prepare within logged_in.php
Also, what's a good source to learn step by step. I tried http://php.net/manual/ but that isnt making sense to me.
Thank you!

use php frameworks. so that it is fast and easy. Here login controller ive used in codeigniter framework
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('login_model', 'lm');
$this->load->model('posts_model', 'pm');
date_default_timezone_set('Asia/Hong_Kong');
}
//check password in the database
public function check_database($password){
$username = $this->input->post('username');
$result = $this->lm->login($username, $password);
if($result){
$sess_array = array();
foreach($result as $row){
$sess_array = array(
'id'=>$row->user_id,
'username'=>$row->username,
);
$this->session->set_userdata('loggedIn', $sess_array);
}
return true;
}else{
$this->form_validation->set_message('check_database', 'Invalid Username or Password.');
return false;
}
}
public function auth(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE){
$this->index();
}else{
redirect('post');
}
}
public function index(){
$data['title'] = "Login here | OkDito.ph Cebu's # 1 Buy and Sell Website";
$data['great_deals'] = $this->pm->greatdeals();//get all items
$data['getAllPendingPosts'] = $this->pm->getAllPendingPosts();
$tmp_pending = array();
$tmp_pending = $data['getAllPendingPosts'];
if(!empty($tmp_pending )){
$pending = 1;
}
else{
$pending = 0;
}
$data['pending'] = $pending;
if($this->session->userdata('loggedIn')){
$login = $this->session->userdata('loggedIn');
if(!empty($login)){
redirect('post');
}
}
else{
$this->template_lib->set_view('index_view', 'login_view', $data,'',$data);
}
}
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* User library for the Model..all commonly used functions should be placed here
* #author: team gabayan
* #created: 7/1/11
*/
class Login_model extends CI_Model{
//check if email exist in the database
public function email($email){
$this->db->select(
'tbl_users.email'
)
->from('tbl_users')
->where('email', $email);
$q = $this->db->get();
if($q->num_rows() == 1){
return $q->result();
}else{
return false;
}
}
Here. Hope this helps
public function login($username, $password){
$sha_password = sha1($password);
$this->db->select(
'tbl_users.user_id,
tbl_users.username,
tbl_users.password,
tbl_users.status
'
)
->from('tbl_users')
->where('tbl_users.username', $username)
->where('tbl_users.password', $sha_password);
$query = $this->db->get();
if($query->num_rows() == 1){
return $query->result();
}else{
return false;
}
}
}//endclass
/End of File Login_model.php/
/File Location: ./application/models/login_model.php/

Related

password_verify() logging in all the time

Using codeigniter hashed my password with BCRYPT, seems that everytime I login I redirect to the success page. So I am figuring password verify is not working, even if I enter the incorrect login it still redirects, does not throw the form_validation errors either.
I used the documentation to set it up along with the guides on SO. Will eventually go to Ion Auth but want to know how to fix this. As I am still learning code igniter mvc.
Model
class user_model extends CI_Model{
public function register($encrypt_pass){
$data = array(
'name'=> $this->input->post('name'),
'email'=> $this->input->post('email'),
'username'=> $this->input->post('username'),
'password'=>password_hash($encrypt_pass,PASSWORD_BCRYPT)
);
return $this->db->insert('customers',$data);
}
public function login($username,$password){
//validate the inputs from form
$this->db->where('username',$username);
$query = $this->db->get('customers'); //customers is the table
$result = $query->row_array();
if(!empty($result) && password_verify($password, $result['password'])){
return $result;
}
else{
return "false";
}
}
}
Controller
public function login()
{
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run()=== FALSE){
$this->load->view('templates/header');
$this->load->view('users/login',$data);
$this->load->view('templates/footer');
}
else {
//Getting username
$username = $this->input->post('Username');
//Getting and ecrypting password
$password = $this->input->post('Password');//password hashed
$user_id = $this->user_model->login($result);
//checking for user/pass correct will set session if so
if($user_id){
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('posts');
}
// If combo is incorrect will redirect
else{
$this->session->set_flashdata('user_loggedin','Login Failed, Please Try
Again');
redirect('users/login');
}
}
}
}
Here is a simple working login code, there are many ways how to do it, it's just an example.
ON YOUR MODEL
Create a function that will check/get the username's password.
public function _getUserPassword($user_name){
$data = array();
$this->db->select('PASSWORD');
$this->db->from('tbl_user');
$this->db->where('USER_NAME', $user_name);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach($query->result_array() as $field_name => $field_value){
$data = $field_value;
}
return $data;
}
else{
return false;
}
}
I've seen your's just selecting it.
We need to use that _getUserPassword function on we call it verify function
function verify($username, $password){
$data = array();
$userNameExists = $this->_getUserPassword($username);
if(password_verify($password, $userNameExists['PASSWORD'])){
$this->db->select('*');
$this->db->from('tbl_user AS user');
$this->db->where('USER_NAME', $username);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach($query->result_array() as $field_name => $field_value){
$data = $field_value;
}
return $data;
}
else{
return false;
}
}
else{
return false;
}
}
So if the verification is success it will return the data to your controller, Let's use your controller.
Let's assume that you changed the models
ON YOUR CONTROLLER
public function login()
{
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run()=== FALSE){
$this->load->view('templates/header');
$this->load->view('users/login',$data);
$this->load->view('templates/footer');
}else {
//Getting username
$username = $this->input->post('Username');
//Getting and ecrypting password
$password = $this->input->post('Password');
$user_id = $this->user_model->verify($username,$password);
//checking for user/pass correct will set session if so
if($user_id){
$this->session->set_userdata('user_loggedin','You are now logged in');
redirect('posts');
}else{
//DO NOT SET USER DATA SESSION HERE UNLESS IT WILL AUTOMATICALLY LOGGED IN.
redirect('users/login');
}
}
}
Hope this helps!
where you are checking that password is matching or not.
try this in your controller.after user check.
if($user>0){
if (password_verify($this->input->post('Password'), $user_id['password'])) {
//success message
}
else{
//error message.password is invalid
}

change password in codeigniter with logged in users throws error

I want to change the password for logged in users,but it always give me an error:[Message: Trying to get property 'password' of non-object] in the controller. How to solve this error???
Please help,Thanks much!
This is my controller:
if($this->form_validation->run()){
$cur_password = md5($this->input->post('cpassword')); // md5-encrypt the password
$new_password = md5($this->input->post('npassword'));
$conf_password = md5($this->input->post('copassword'));
//$this->load->model('queries');
$this->load->library('session');
$user_id = $this->session->userdata('user_id');//multiple users id login
$passwd = $this->queries->getCurPassword($user_id);
!ERROR FOUND HERE!->if($passwd->password == $cur_password){
if($new_password == $conf_password){
if($this->queries->updatePassword($new_password,$user_id)){
echo 'Password Updated Successfully!';
echo '<br/><label>Back to homepage</label><br/>';
}else{
echo 'Failed To Update Password!!';
}
}else{
echo 'New Password and Confirm Password is not matching!!';
}
}else{
echo 'Sorry! Current Password is not matching!!';
}
}else{
echo validation_errors();
}
This is my model:
<?php
class Queries extends CI_Model{
function login() {
$query = $this->db->select('*')
->from('users')
->where('id');
return $query->row();
}
function index() {
$userid = $this->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('user_id', $user_id);
}
public function getCurPassword($user_id){
$query = $this->db->where(['id'=>$user_id])
->get('users');
if($query->num_rows() > 0 ){
return $query->row();
}
}
public function updatePassword($new_password,$user_id){
$data = array(
//'password' => md5($this->input->post("$new_password"))
'password' => ($new_password)
//'password'=> password_hash(["$new_password"],PASSWORD_BCRYPT)
);
return $this->db->where('id',$user_id)
->update('users',$data);
}
}
Thanks!
You have error in your syntax error says that you are trying to get property of non-object means $passwd may be an array
if($passwd['password'] == $cur_password)
And in case you have null user_id
Place these two lines in your controller function above if($this->form_validation->run()){ line
$userid = $this->queries->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('user_id', $userid);
and in your login function in model
function login() {
$query = $this->db->select('*')
->from('users')
->where('username',$this->session->userdata('username'));
return $query->row();
}
Hope it helps!
This happens when the user_id not found.
Notice that the getCurPassword function will return the user if found (when checking if num_rows > 0) but if didn't found it returns NULL.
When this happens the $passwd var is null so you cann't access $passwd->password.
You can solve it by changing the if statement to:
if($passwd && $passwd->password == $cur_password){
Edited Try to retrieve your user name as and then call with it the getCurPassword function:
$user_name = $this->session->userdata('username');
$passwd = $this->queries->getCurPassword($user_name );
And in the controller change getCurPassword function as:
public function getCurPassword($user_name){
$query = $this->db->select('*')
->from('users')
->where('username', $user_name);
if($query->num_rows() > 0 ){
return $query->row();
}
}
Notice that I assume you have "username" column in your DB

adding user id from database to session data in Codeigniter?

i am new to CodeIgniter and facing problem in adding user id(after user has logged in) from database to session data here is my code question may be asked before on SOF , after putting all my efforts i am asking this
//login-model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//get the username & password from tbl_usrs
public function get_user($usr, $pwd)
{
$sql = "select * from tbl_usrs where username = '" . $usr . "' and password = '" .$pwd . "' ";
$query = $this->db->query($sql);
return $query->num_rows();
}
/* public function set_session($username) {
$sql="SELECT * FROM tbl_usrs WHERE username='".$username."' LIMIT 1 ";
$result=$this->db->query($sql);
$row=$result->row();
$sess_data=array (
'id'=>$row->id,
'username'=>$username,
'is_login'=>TRUE
);
$this->session->set_userdata($sess_data);
} //set_seesion function ends
*/
}
?>
//login controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
print_r( debug_backtrace() );
//ini_set('memory_limit', '-1');
//ini_set('max_execution_time', 3000);
ini_set('display_errors',1);
error_reporting(E_ALL);
class LoginController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
$this->load->database();
$this->load->library('form_validation');
}
public function index()
{
//load the login model
$this->load->model('login_model');
// $qry=$this->login_model->validate();
//get the posted values
$username = $this->input->post("username");
$password = $this->input->post("password");
$user_id = $this->input->get("user_id");
//set validations
$this->form_validation->set_rules("username", "username", "trim|required");
$this->form_validation->set_rules("password", "password", "trim|required");
if ($this->form_validation->run() == FALSE)
{
//validation fails
redirect('Homecontroller/index'); //make new controller for loading a form again
echo "Validation fails"; // even for no name and passwrd
}
else
{
//validation succeeds
if ($this->input->post('submit') == "Login")
{
//check if username and password is correct
$usr_result = $this->login_model->get_user($username, $password);
if ($usr_result > 0) //active user record is present
{
//set the session variables
$sessiondata = array(
'user_id' => $user_id,
'username' => $username,
'password'=>$password,
'is_login' => TRUE
);
//$this->login_model->set_session($username);
$this->session->set_userdata($sessiondata);
print_r($this->session->all_userdata()); //to check
redirect(base_url("Site/member_area"));
return $username;
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username and password!</div>');
redirect('Homecontroller/index');
}
}
else
{
redirect('login/home3');
}
}
}
}?>
when i am try to print session data in view i am getting user_id=> empty
None of these variables will be available to you for assignment:
'user_id' => $user_id,
'username' => $username,
'password'=>$password,
The reason for this is that you've used:
$usr_result = $this->login_model->get_user($username, $password);
However, that is only going to be the result of the number of rows returned:
public function get_user($usr, $pwd)
...
return $query->num_rows();
So now, $usr_result will be the number of rows returned, not the data of the user in question.
So, what you should do, is instead set the session data in that login function above return $query->num_rows(); and below $query=.
public function get_user($usr, $pwd){
....
$query = $this->db->query($sql);
$this->session->set_userdata('sessiondata', $query->row_array());
}
Note that as we only retrieve 1 user from our query ever, we also would only ever want to get 1 row back. Furthermore, you're wanting to store an associative array, and not an object, so we use $query->row_array() to get back 1 row formatted as an array where the key is the column name and the value is the columns result.
Now, do a echo '<pre>', print_r($this->session->userdata('sessiondata'), true),'</pre>'; to get a formatted list of that object which contains the array. Then you can map names accordingly.
Sidenote, i would not store the password in an session.

How to Update Data in CodeIgniter?

First, sorry for my bad english, if you don't understand what I'm saying, you can ask for it and I will search for another suitable and precise words.
Now, I've been working with codeigniter in this last 2 weeks, so I got so many question for it, but I found 1 which is hanging on my mind.
I started with simple CRUD, then make it advanced, it's good so far, until I got stuck while updating data. When I click the "submit" button, I get only 404 page. And when I see the database, nothing change.
Here's the controller's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Master_user extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('mod_master_user');
$this->load->library('datatables');
}
public function index(){
if ($this->session->userdata('type') == 'admin') {
$data['hasil'] = $this->mod_master_user->getall();
$datum['content'] = $this->load>view('master_user/view',$data,true);
$this->load->view('main',$datum);
} else if ($this->session->userdata('type') == 'user'){
$a= $this->load->model('m_absensi');
$aa["content"] = $this->load->view('absensi/form',$a,true);
$this->load->view("absensi/mainUser",$aa);
}
}
public function tambah_data(){
if($this->input->post('nama')){
$this->mod_master_user->tambah();
redirect('master_user');
}else{
$this->load->view('master_user/add');
}
}
public function update_data($id_user)**//i use this method for updating data**{
if($this->input->post('submit')){
$this->mod_master_user->update($id_user);
redirect('master_user/index');
}
$data['hasil']=$this->mod_master_user->getById($id_user);
$this->load->view('master_user/edit',$data);
}
public function delete_data($id_user){
$this->mod_master_user->delete($id_user);
redirect('master_user');
}
public function error()
{
$this->output->set_status_header('404');
$data['content'] = '404';
$this->load->view('master_user/404',$data);
}
public function print_report()
{
$this->load->view('master_user/print');
}
public function jam_masuk()
{
$this->load->view('master_user/jam_masuk');
}
}
Here comes the model's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Mod_master_user extends CI_Model{
var $tabel_name = 'master_user';
function __construct() {
parent::__construct();
}
public function getall(){
$ambil_data = $this->db->get('master_user');//mengambil tabel master_user
if ($ambil_data->num_rows() > 0 ){ //jika data lebih dari 0
foreach ($ambil_data->result() as $data){
$hasil[] = $data;
}
return $hasil;
}
}
public function tambah(){
$id_user = $this->input->post('id_user');
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$tanggal_lahir = $this->input->post('tanggal_lahir');
$tempat_lahir = $this->input->post('tempat_lahir');
$role = $this->input->post('role');
$data = array (
'id_user'=> $id_user,
'nama'=>$nama,
'password'=>md5($password),
'tanggal_lahir'=>date('Y-m-d',strtotime($tanggal_lahir)),
'tempat_lahir'=>$tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->insert('master_user', $data);
}
public function update($id_user)**//i use this method to updating data**{
$id_user=$this->input->post('id_user');
$nama=$this->input->post('nama');
$password=$this->input->post('password');
$tanggal_lahir=$this->input->post('tanggal_lahir');
$tempat_lahir=$this->input->post('tempat_lahir');
$role=$this->input->post('role');
$data = array (
'id_user' => $id_user,
'nama' => $nama,
'password'=> $password,
'tanggal_lahir'=> $tanggal_lahir,
'tempat_lahir'=> $tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->update('master_user',$data); //update data
}
public function getById($id_user){ //mengambil data dari db berdasarkan id (primary key)
return $this->db->get_where('master_user',array('id_user'=>$id_user))->row();
}
public function delete($id_user){
$this->db->where('id_user',$id_user);
$this->db->delete('master_user'); //query delete data
}
public function cek_user_login($username, $password) {
$this->db->select('*');
$this->db->where('NAMA', $username);
$this->db->where('PASSWORD', md5($password));
$query = $this->db->get($this->tabel_name, 1);
if ($query->num_rows() == 1) {
$this->db->limit(1);
return $query->row_array();
}
}
public function validasi()
{
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$check = $this->mod_master_user->check($nama, md5($password));
if($check->num_rows() > 0)
{
//login berhasil, buat session
//$this->session->set_userdata('username',$username);
redirect('master_user');
}
else
{
//login gagal
//$this->session->set_flashdata('message','Username atau password salah');
redirect('users');
}
}
}
So far, I get no answer on other forums, so I asked for the answer here :)
Any answer/help will be appreciated. Thank you :)
It's been some time since I used CodeIgniter.
Are you loading the input class? so you can actually receive $_GET and $_POST data? I think it does this by default actually.
This might be a bit too simple, but are you calling the right URI and are you sure its reaching your view??
Might help to see your view, are you using the form helper for this? https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html
If you get 404, then the problem is in your form action tag. It means it doesn't post to the right url.
This is most likely (if not surely) due to a bad route.
In config/routes.php, you need a route like: $route['master_user/update/(:any)'] = 'master_user/update_data/$1;
And in your view you would need a form with the action pointing to that route, such as:
<form action="master_user/update_data/1">
<!-- your fields and submit button -->
</form>
Where the number 1 (in the action url) is the id of the register being updated.

How to take specific data from table and store it in a cookie codeigniter php?

I'm new to codeigniter and php, few days only, so I need a little help.
I'm trying to put some data in my cookie from table so I can check where to redirect user after login. In table users there are two columns named Admin and Company with one or zero if user is or not, and then i wish to insert that information to cookie.
function conformation in user_controler is:
function conformation(){
$this->load->model('user');
$q = $this->user->confr();
if($q){
$data = array(
'username' => $this->input->post('username'),
'Admin' => $this->input->post($a = $this->user->getAdmin), // get 1/0 from users column Admin
'Company' => $this->input->post($c = $this->user->getComp),
'login' => true
);
if( $a == 1 ){ //is admin redirect to admin view
$this->session->set_userdata($data);
redirect('user_controler/useradm');
}
if($c == 1){ //if company redirect to company view
$this->session->set_userdata($data);
redirect('user_controler/usercomp');
}
$this->session->set_userdata($data);// if common user redirect to user view
redirect('user_controler/userpro');
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
And in user model:
function getAdmin{
$this->db->where('Admin', 1);
$a = $this->db->get('users');
}
function getComp{
$this->db->where('Company', 1);
$a = $this->db->get('users');
}
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Also have site controller for checking login
class Site extends CI_Controller{
function __construct() {
parent::__construct();
$this->login();
}
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || login != TRUE){
$this->log;
die();
}
}
}
Of course it's not working because i should probably check these column some other way but I don't know how. I Also have enabled table ci_session and it's work perfectly without Admin and Company.
Hello and welcome to Stackoverflow.
Here are my updates to the code (I have annotated my changes):
function conformation(){
$this->load->model('user');
if($this->user->confr()){ //$q wasn't needed, as you are only using this twice
$user = $this->input->post('username'); //I have added this as I will be referring to it a couple of times.
$data = array(
'username' => $user,
'Admin' => $this->user->getAdmin($user), // Your method was questioning the original form looking for data that it would never find - This will question your model.
'Company' => $this->user->getComp($user), //Same as above
'login' => true
);
$this->session->set_userdata($data); //It doesn't matter who the user is, we shall set the data to start with.
if($this->user->getAdmin($user)){ //is admin redirect to admin view
redirect('user_controler/useradm');
}
elseif($this->user->getComp($user)){ //if company redirect to company view
redirect('user_controler/usercomp');
}
else { //Redirect non-privileged users.
redirect('user_controler/userpro');
}
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
Users Model:
function getAdmin($user){
$this->db->where('username', $user); //Before you was just returning everyone who is an admin This instead finds the user
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Admin"]==1) { return true; } //This finds if the user is a admin or not, and the function will now return a value (true)
}
}
function getComp($user) {
$this->db->where('username', $user);
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Company"]==1) { return true; }
}
} //Edited similar to the function above
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Lastly your login function:
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || $login != TRUE){ //You weren't referring to your $login variable
$this->log;
die();
}
}
Hopefully this helps with your problems, let me know if you need any amendments.

Categories