session not regestring the 3 variable - javascript

I have created a login system in codeigniter. It's working fine, but when i login it registers only 2 variable which are login and password but not showing me the 3rd variable in the session which is user_type. I have tried too much but i can not understand what is wrong.
model code
function login($username, $password) {
//create query to connect user login database
$this->db->select('user_id, username, password','user_type');
$this->db->from('login');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status',1);
$this->db->limit(1);
//get query and processing
echo $query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result(); //if data is true
} else {
return false; //if data is wrong
}
}
varifying code controller
function index() {
$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->load->view('v_login');
} else {
//Go to private area
redirect(base_url('c_home'), 'refresh');
}
}
function check_database($password) {
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->login->login($username, $password);
if($result) {
$sess_array = array();
foreach($result as $row) {
//create the session
$sess_array = array('user_id' => $row->user_id,
'username' => $row->username,
'user_type'=> $row->user_type
);
//set session with value from database
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
//if form validate false
$this->form_validation->set_message('check_database', '<p style="color: red;">اسم المستخدم / كلمة المرور غير صحيحة ! </p>');
return FALSE;
}
}
session variable code
function session_start(){
/*---------------------------- session start here */
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['id'] = $session_data['user_id'];
$data['user_type'] = $session_data['user_type'];
} else {
//If no session, redirect to login page
redirect('c_login', 'refresh');
}
/* ---------------------- session start ends */

Because you are not selecting user_type in your select query.
Change this :
$this->db->select('user_id, username, password','user_type');
With this :
$this->db->select('user_id, username, password,user_type');

Related

Validate login form with JS/PHP

I want to be able to either send a user to a restricted area or return some text that says Email and or password do not exist or something similar. I'm having trouble getting this to work as whether or not the email and password are correct NOTHING happens. I'm sending the form to the index page where the script to run this sits. Not sure why I'm not redirecting or getting any kind of errors.
The restricted page checks if a $_SESSION variable isset(), if not then send them back home.
JS
loginBtn.addEventListener('click', e => {
e.preventDefault();
ajaxRequests.login(`login_email=${ loginEmail.value }&login_password=${ loginPassword.value }`);
});
ajaxRequests.login()
login(formData) {
return new Promise((resolve, reject) => {
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.send(formData);
this.xhr.onload = () => {
if (this.xhr.status == 200) {
resolve();
} else {
reject(this.xhr.statusText);
}
};
this.xhr.onerror = () => {
reject(this.xhr.statusText);
};
});
}
this is the script that is supposed to run when form is sent
if (isset($_POST['login_email']) && isset($_POST['login_password'])) {
$email = htmlentities($_POST['login_email'], ENT_QUOTES, 'ISO-8859-15');
$password = htmlentities($_POST['login_password'], ENT_QUOTES, 'ISO-8859-15');
$login = new Login($email, $password);
unset($login);
}
check for valid $_SESSION vars
session_start();
if (!isset($_SESSION['id']) || !isset($_SESSION['name']) || !isset($_SESSION['email'])) {
header('Location: index.php');
}
login query (just incase it is needed)
class Login extends Connection {
public function __construct($email, $password) {
$this->connect();
$sql = "SELECT `id`, `name`, `email`, `password` FROM `users` WHERE `email`=:email";
$query = $this->connect()->prepare($sql);
$result = $query->execute(
[
':email' => htmlentities($email, ENT_QUOTES, 'ISO-8859-15'),
]
);
// check if EMAIL exists
if ($result) {
$row = $query->fetch(PDO::FETCH_OBJ);
$id = htmlentities($row->id, ENT_QUOTES, 'ISO-8859-15');
$name = htmlentities($row->name, ENT_QUOTES, 'ISO-8859-15');
$email = htmlentities($row->email, ENT_QUOTES, 'ISO-8859-15');
$hashed_password = htmlentities($row->password, ENT_QUOTES, 'ISO-8859-15');
// check if user input PASSWORD matches the unhashed PASSWORD in the database
if (password_verify($password, $hashed_password)) {
$_SESSION['id'] = htmlentities($id, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['name'] = htmlentities($name, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['email'] = htmlentities($email, ENT_QUOTES, 'ISO-8859-15');
header('Location: blog_roll.php');
} else {
header('Location: index.php');
}
} else {
echo 'THAT EMAIL ADDRESS DOES NOT EXIST';
}
}
}
You have to set the content type for your ajax request
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.xhr.send(formData);

Sessions in AngularJS and PHP application

I have an AngularJS application that I am updating to use PHP 7. Currently I have a custom session handler setup for sessions:
Custom Session Handler (session.php)
function sess_open( $path, $name ) {
return true;
}
function sess_close( ) {
$sessionId = session_id();
return true;
}
function sess_read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
return $data;
}
function sess_write( $id, $data ) {
$db = dbConn::getConnection();
$tstData = sess_read( $id );
if (!is_null($tstData)) {
// if it does then do an update
$stmt = "UPDATE session SET session_data =" . $db->quote($data) . " WHERE session_id=" . $db->quote($id);
$db->query($stmt);
}
else {
// else do an insert
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ")";
$db->query($stmt);
}
return true;
}
function sess_destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
return $db->query($stmt);
}
function sess_gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
return $db->query($stmt);
}
session_name('PROJECT_CUPSAW_WEB_APP');
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
ob_flush();
In my app.js I have a continuous check to see if the user is authenticated and can access the application.
App.js
/*
* Continuous check for authenticated permission to access application and route
*/
app.run(function($rootScope, $state, authenticationService, ngToast) {
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
authenticationService.isAuthenticated()
.success(function () {
if(toState.permissions) {
ngToast.dismiss();
event.preventDefault();
$state.go("logout"); // NEEDS TO CHANGE - Unauthorized access view
return;
}
})
.error(function () {
ngToast.dismiss();
event.preventDefault();
localStorage.clear();
$state.go("authentication"); // User is not authenticated; return to login view
return;
});
ngToast.dismiss();
});
});
In the code above, isAuthenticated runs isUserAuthorized.php
isAuthenticated
/*
* Check if user is authenticated; set role/permissions
*/
this.isAuthenticated = function() {
return $http.post(baseUrl + '/isUserAuthorized.php');
};
isUserAuthorized.php
<?php
require_once 'session.php';
// Check to ensure user is authenticated to initiate request
if (array_key_exists('authenticated', $_SESSION) && $_SESSION['authenticated']) {
return http_response_code(200);
} else {
// Clear out all cookies and destroy session
if( array_key_exists('HTTP_COOKIE', $_SERVER)){
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
session_destroy();
return http_response_code(401);
}
The session should be started when session.php is required. It appears that this is not happening though. Upon accessing the application, the login page is displayed, but isUserAuthorized.php is throwing a warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
When I select the Login button, login.php is called, but the user gets brought right into the application, despite incorrect credentials.
login.php
<?php
require_once '../database.php';
require_once 'session.php';
require_once 'ldap.php';
$_SESSION['authenticated'] = false;
//$conn = connect_db();
try {
$data = json_decode(file_get_contents('php://input'));
$username = strtolower($data->username);
$password = $data->password;
// Check domain credentials; return user token if verified
if(ldap_authenticate($username, $password)) {
$_SESSION['authenticated'] = true;
}
else {
echo('Invalid username and/or password!');
return http_response_code(400);
}
}
catch(PDOException $e) {
return http_response_code(400);
}
I'm not entirely sure what's causing this odd behavior, and why the session isn't being created. Do I need to explicitly call the sess_write function?
Update
I discovered that removing the require_once 'session.php' from login.php causes the proper behavior. The user is able to login when they provide valid credentials. However, the session data is still never being written to the database. Any idea why?
The issues came down to my session handler. As of PHP 7, the sess_read function must return a string. This was causing the warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
I fixed this by returning '' when $data was null.
This caused issues with my sess_write function knowing when to insert and when to update. I fixed this by changing the SQL.
Ultimately I ended up making the session handler a class, as shown in the final result:
<?php
require_once ('../database.php');
class CustomSessionHandler implements SessionHandlerInterface{
public function open( $path, $name ) {
return true;
}
public function close( ) {
return true;
}
public function read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
if(!$data){
return '';
}
return $data;
}
public function write( $id, $data ) {
$db = dbConn::getConnection();
//Works with Postgres >= 9.5
//$stmt = "INSERT INTO session (session_id, session_data) VALUES (" . $db->quote($id) . ", " . $db->quote($data) . ") ON CONFLICT (session_id) DO UPDATE SET session_data=" . $db->quote($data) . ";";
//Works with Postgres < 9.5
$stmt = "UPDATE session SET session_data=" . $db->quote($data) . " WHERE session_id=" . $db->quote($id) . ";";
$db->query($stmt);
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ");";
$db->query($stmt);
return true;
}
public function destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
$data = $db->query($stmt);
return true;
}
public function gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
$data = $db->query($stmt);
return true;
}
}
session_name('PROJECT_CUPSAW_WEB_APP');
$handler = new CustomSessionHandler();
session_set_save_handler($handler, false);
session_start();
ob_flush();

Call to undefined method mysqli_stmt::get_result() on line 43 [duplicate]

This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 6 years ago.
I have a small problem. When I try to login on a script I worked on I can not login. I hope you guys can help me out. For some reason I get this MySQL error:
Call to undefined method mysqli_stmt::get_result() in
home/[username]/public_html/inc/session.php on line 43
The code for session.php:
<?php
class Session {
private $self_file = 'session.php';
private $mysqli = false;
public function __construct($m) { $this->mysqli = $m; }
public function isLogged() {
if(!isset($_SESSION['invento_logged']) || !is_array($_SESSION['invento_logged']))
return false;
if(!isset($_SESSION['invento_logged']['u']) || !isset($_SESSION['invento_logged']['p']))
return false;
$u = $_SESSION['invento_logged']['u'];
$p = $_SESSION['invento_logged']['p'];
$prepared = $this->prepare("SELECT count(*) as c FROM invento_users WHERE username=? && password=?", 'isLogged()');
$this->bind_param($prepared->bind_param('ss', $u, $p), 'isLogged()');
$this->execute($prepared, 'isLogged()');
$result = $prepared->get_result();
$row = $result->fetch_object();
if($row->c == 1)
return true;
return false;
}
public function refresh_password($pass) {
$_SESSION['invento_logged']['p'] = md5($pass);
return true;
}
public function login($u, $p) {
$p = md5($p);
$prepared = $this->prepare("SELECT count(*) as c FROM invento_users WHERE username=? && password=?", 'isLogged()');
$this->bind_param($prepared->bind_param('ss', $u, $p), 'login()');
$this->execute($prepared, 'login()');
$result = $prepared->get_result();
$row = $result->fetch_object();
if($row->c != 1)
return false;
$_SESSION['invento_logged']['u'] = $u;
$_SESSION['invento_logged']['p'] = $p;
return true;
}
public function logout() {
if(isset($_SESSION['invento_logged']))
$_SESSION['invento_logged'] = false;
unset($_SESSION);
session_destroy();
return true;
}
public function get_user_id() {
$username = $_SESSION['invento_logged']['u'];
$prepared = $this->prepare("SELECT id FROM invento_users WHERE username=?", 'get_user_id()');
$this->bind_param($prepared->bind_param('s', $username), 'get_user_id()');
$this->execute($prepared, 'get_user_id()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->id;
}
public function get_user_name_by_id($id) {
$prepared = $this->prepare("SELECT username FROM invento_users WHERE id=?", 'get_user_name_by_id()');
$this->bind_param($prepared->bind_param('i', $id), 'get_user_name_by_id()');
$this->execute($prepared, 'get_user_name_by_id()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->username;
}
public function get_user_role() {
$id = $this->get_user_id();
$prepared = $this->prepare("SELECT role FROM invento_users WHERE id=?", 'get_user_role()');
$this->bind_param($prepared->bind_param('i', $id), 'get_user_role()');
$this->execute($prepared, 'get_user_role()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->role;
}
/***
* Private functions
*
***/
private function prepare($query, $func) {
$prepared = $this->mysqli->prepare($query);
if(!$prepared)
die("Couldn't prepare query. inc/{$this->self_file} - $func");
return $prepared;
}
private function bind_param($param, $func) {
if(!$param)
die("Couldn't bind parameters. inc/{$this->self_file} - $func");
return $param;
}
private function execute($prepared, $func) {
$exec = $prepared->execute();
if(!$exec)
die("Couldn't execute query. inc/{$this->self_file} - $func");
return $exec;
}
private function query($query, $func) {
$q = $this->mysqli->query($query);
if(!$q)
die("Couldn't run query. inc/{$this->self_file} - $func");
return $q;
}
public function __destruct() {
if(is_resource($this->mysqli) && get_resource_type($this->mysqli) == 'mysql link')
$this->mysqli->close();
}
}
$_session = new Session($mysqli);
and the code for config.php:
<?php
session_start();
/************ You can edit details starting from here ************/
$dbhost = '(I've filled this in'; // Write your MySQL host here.
$dbuser = 'I've filled this in'; // Write your MySQL User here.
$dbpass = 'I've filled this in'; // Write your MySQL Password here.
$dbname = 'I've filled this in'; // Write the MySQL Database where you want to install
/************ DON'T EDIT NOTHING BELOW ************/
if(!isset($noredir) && $dbhost == 'localhost' && $dbuser == 'MYSQL USERNAME' && $dbpass == 'MYSQL PASSWORD')
header('Location:install.php');
if(!isset($noredir)) {
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno)
die('<h2>Something went wrong while trying to connect to your MySQL Database. Error No. ' . $mysql->connect_errno.'<h2>');
// Check existance of random table to test installed system
$tables = array('users','categories','items','logs','settings');
$rn = rand(0,4);
$res = $mysqli->query("SHOW TABLES LIKE '%invento_{$tables[$rn]}%'");
if($res->num_rows == 0)
header('Location:install.php');
}
I hope you guys can help me out.
Thanks in advance,
Bram
I think it's because of the version of PHP that you are using.
As mentioned in php documentation mysqli_stmt::get_result, this method is supported since PHP 5.3.0.
And it is stated in the user notes section that:
This method requires the mysqlnd driver. Othervise you will get this error: Call to undefined method mysqli_stmt::get_result()
Instead of this function, try using bind_result function.
Helpful link
http://php.net/manual/en/mysqli-stmt.get-result.php

Session variables are not being set, php sql

So my problem is that i'm trying to check if some session variables are set, and they should be, but when I check them they dont have a value.
So first of I have this HTML form that takes an Email and Password input
HTML CODE:
<form class="login_form" action="includes/process_login.php" method="POST" name="login_form">
<input type="text" placeholder="Email" name="email">
<input type="password" placeholder="Password" name="password" >
<input type="button" value="LOGIN" class="login_button" onclick="formhash(this.form, this.form.password);">
</form>
And as you can see my submit button first of all goes to a javascript that hashes the input.
JAVASCRIPT CODE:
function formhash(form, password) {
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
}
And after it is done hashing the password it sends the form information to the target which is "includes/process_login.php"
PROCESS_LOGIN.PHP CODE:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: ../protected_page.php');
} else {
// Login failed
header('Location: ../index.php?error=1['.$email.', '.$password.']');
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
And from here it sends the $email and $password values into the function login:
FUNCTION LOGIN CODE:
function login($email, $password, $mysqli){
if($stmt = $mysqli->prepare("SELECT id, username, password FROM users WHERE email = ? LIMIT 1")){
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password);
$stmt->fetch();
if($stmt->num_rows == 1){
if(checkbrute($user_id, $mysqli) == true){
return false;
}else{
if (password_verify($password, $db_password)) {
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$db_password . $user_browser);
return true;
}else{
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
}else{
return false;
}
}
}
Now here comes part of the problem, in this code it stores a session:user_id values, session:username value and session:login_string value.
But the problem is that the session does not get stored anything.
Because when I then get redirected to the so called "protected_page.php" it then checks if these values are set or not and returns that they are not set.
THE LOGIN_CHECK CODE ( that checks if we are logged in or not)
function login_check($mysqli){
if (isset($_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['login_string']
)) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
echo $user_id;
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT password
FROM users
WHERE id = ? LIMIT 1")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if (hash_equals($login_check, $login_string) ){
return true;
}else{
return false;
}
}else{
return false;
}
}else{
return false;
}
}else{
return false;
}
}
Sorry about this post being very long, but I could really need some new angles. Thanks!
PS Here is the "custom set session function"
function sec_session_start(){
$session_name = 'sec_session_id';
session_name($session_name);
$secure = true;
$httponly = true;
if(ini_set('session.use_only_cookies', 1) === FALSE){
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
session_start();
session_regenerate_id(true);
}

disable button when username is taken jquery

I would like to be able to have my form disabled from submitting when username is taken, and I would like to get some help with that.
my js code is:
$('#username').keyup(function() {
var username = $(this).val();
$('#username_status').html('Searching...');
if (username !='') {
$.post('username_check.php', { username: username}, function(data) {
$('#username_status').html(data);
});
} else{
$('#username_status').html('');
}
});
and my for checking username exists or not:
<?php
if(isset($_POST["username"]))
{
define("HOST","localhost");
define("USERNAME","root");
define("PASS","");
define("DBNAME","testingproject");
$connecDB = mysqli_connect(HOST, USERNAME, PASS, DBNAME)or die('could not connect to database');
$username = $_POST["username"];
$results = mysqli_query($connecDB,"SELECT id FROM attendant WHERE username='$username'");
$username_exist = mysqli_num_rows($results); //records count
if($username_exist) {
$output= "Sorry, this Username is taken";
echo ($output);
}else{
echo('available');
}
}
?>
on php page
if($username_exist) { echo 'yes'; }
else { echo 'no'; }
on js,
$.post('username_check.php', { username: username}, function(data) {
if (data == 'yes') {
// here disable the registration button
} else {
// active the registration button
}
});
hope it help!
also you can check this thread: JQuery/Ajax Post returned data and IF function

Categories

Resources