How to avoid shared sessions when accessing one domain - php

I am having problems regarding the shared sessions once the users logged in simultaneously to the website. When the last user logs in, every users views the account of the last user, which is not appropriate (security issue I guess). All users must login to the same website and must show an output for a specific user only.
I am using PHP code. Does anyone also experienced these scenario? here's the code
function validate_login(){
$userName= trim((isset($_POST['username']) === TRUE ? $_POST['username'] : ''));
$userPass= trim((isset($_POST['userpass']) === TRUE ? $_POST['userpass'] : ''));
$userNameArray = explode("#", $userName);
$userName = $userNameArray[0];
$compLogin = ((isset($userNameArray[1]) === TRUE ? $userNameArray[1]: ''));
$KeepAlive = new KeepAlive();
if(isset($userNameArray[1])){
if(!$this->Login->checkattempt('admin')){
$loginArray = array(
'login' => $userName,
'comp_login_string' => $compLogin,
'pass' => $cryptography->encryptPassword($userPass)
);
$userCredentials = $this->Login->getLogin($loginArray);
if(!empty($userCredentials)){
$_SESSION['userCredentials'] = $userCredentials[0];
header('Content-Type: application/json');
$_SESSION['employee_user'] = '0';
$_SESSION['emp_id'] = '0';
$_SESSION['page']['client_ip_address'] = $KeepAlive->get_client_ip();
$_SESSION['page']['last_trans_time'] = time();
$this->Login->clear_attempt_log($_POST, 'admin');
echo json_encode(array('id' => $userCredentials[0]['id']));
}
} else {
array_shift($loginArray);
$this->Login->attempt_log($_POST, 'admin');
header('Content-Type: application/json');
echo json_encode(array('id' => '-1'));
}
} else {
echo json_encode(array('id' => '-2'));
}
}

Related

PHP not storing variable values between if

This code is for Telegram bot.
So I was trying to pass the value when user typed 'Category Check', which will return a news title and question asking if it's the correct category.
But after the user answered 'yes', for some reason the variables are reset so $title, $cat, and $check are blank.
How do I fix this?
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
$sender_id = $message['from']['id'];
$sender_first_name = $message['from']['first_name'];
$sender_last_name = $message['from']['last_name'];
$message_date = $message['date'];
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
//when user starts the bot
if (strpos($text, "/start") === 0) {
apiRequestJson("sendmessage", array('chat_id' => $chat_id, "text" => 'Please select an option:', 'reply_markup' => array(
'keyboard' => array(array('Category Check', 'Uncategorized')),
'one_time_keyboard' => false,
'resize_keyboard' => true)));
}
//category check that returns news title and category question to user
else if ($text === "Category Check") {
//MySQL Connection Details
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM `newsdata` WHERE `nb_count` OR `svm_count` <> 0 ORDER BY RAND() LIMIT 1 ";
$row = $result->fetch_assoc();
$nb_business = $row["nb_business"];
$nb_entertainment = $row["nb_entertainment"];
$nb_health = $row["nb_health"];
$nb_politics = $row["nb_politics"];
$nb_science = $row["nb_science"];
$nb_technology = $row["nb_technology"];
$nb_world = $row["nb_world"];
$svm_business = $row["svm_business"];
$svm_entertainment = $row["svm_entertainment"];
$svm_health = $row["svm_health"];
$svm_politics = $row["svm_politics"];
$svm_science = $row["svm_science"];
$svm_technology = $row["svm_technology"];
$svm_world = $row["svm_world"];
$title=$row["title"];
$nb_count=$row["nb_count"];
$svm_count=$row["svm_count"];
if($nb_business!=0)
{$cat='BUSINESS'; $track=1;}
else if ($nb_entertainment!=0)
{$cat='ENTERTAINMENT'; $track=1;}
else if ($nb_health!=0)
{$cat='HEALTH'; $track=1;}
else if ($nb_politics!=0)
{$cat='POLITICS'; $track=1;}
else if ($nb_science!=0)
{$cat='SCIENCE'; $track=1;}
else if ($nb_technology!=0)
{$cat='TECHNOLOGY'; $track=1;}
else if ($nb_world!=0)
{$cat='WORLD'; $track=1;}
else if ($svm_business!=0)
{$cat='BUSINESS'; $track=0;}
else if ($svm_entertainment!=0)
{$cat='ENTERTAINMENT'; $track=0;}
else if ($svm_health!=0)
{$cat='HEALTH'; $track=0;}
else if ($svm_politics!=0)
{$cat='POLITICS'; $track=0;}
else if ($svm_science!=0)
{$cat='SCIENCE'; $track=0;}
else if ($svm_technology!=0)
{$cat='TECHNOLOGY'; $track=0;}
else if ($svm_world!=0)
{$cat='WORLD'; $track=0;}
// output data of each row
//asking user if the category is correct
apiRequestJson("sendmessage", array('chat_id' => $chat_id, "text" => 'Is this news belongs to '.
$cat.' category? '.
$title.' '.$row["link"],
'reply_markup' => array(
'keyboard' => array(array('yes', 'no')),
'one_time_keyboard' => false,
'resize_keyboard' => true)));
}
//user answers
if ($text == "yes" || $text == "no"){
switch ($text) {
case "yes":
$nb_count=$nb_count--;
$svm_count=$svm_count--;
apiRequestJson("sendmessage", array('chat_id' => $chat_id, "text" => $cat.$track.$title."variable check")); //broken here, output: variable check
break;
case "no":
//dothat; break;
}
There are 3 possible solutions to this problem that I can think of depending on how you are re-calling the function.
USE STATIC OR GLOBAL VARIABLES
If the session does not end before you call the function again you could use static variables inside the function or global variables to store the data. If you use the global variable solution then remember to define the variable as "global $your_variable_name" in the function.
USE SESSION VARIABLES OR COOKIES
If the session will end before function calls but will be called again by the same user then you could use session variables of browser cookies to store the data that you want to remain persistent.
STORE THE PERSISTENT VALUES IN A DATABASE
From the title of your question I think that you may need the values to be persistent between calls from multiple users. If this is the case then you will need to store the persistent values in a database such as mySQL.

Persist filter values in codeigniter with pagination library

I use the default codeiginter pagination library. I tried implementing this in a previously created page which shows all vacancies, but since we are getting TOO many on the site, the performance is terrible. This is why I need pagination on this page. Note that this is not the cleanest solution, there is a new track going on which overhauls the entire page and starts from scratch. This is a quick & dirty solution because we need to keep it working on our live environment until the rework is done.
This is the controller code I have:
public function overviewVacancies($city = null)
{
$this->is_logged_in();
// Load Models
$this->load->model('vacancy/vacancies_model');
$this->load->model('perk/interests_model');
$this->load->model('perk/engagement_model');
$this->load->model('user/userSavedVacancies_model');
// Passing Variables
$data['title'] = lang("page_title_activities_overview");
$data['description'] = lang('meta_desc_activities');
$data['class'] = 'vacancy';
$data['engagements'] = $this->engagement_model->getAll();
$data['interests'] = $this->interests_model->getAllInterests();
$data['bread'] = $this->breadcrumbmanager->getDashboardBreadcrumb($this->namemanager->getDashboardBreadName("0"), $this->namemanager->getDashboardBreadName("1"));
$data['tasks'] = $this->interests_model->getAllTasks();
// Set session data
$this->session->set_userdata('previous',"http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
$this->session->set_userdata('previous-title', "1");
$filterdata = array(
'interests' => $this->input->post('interests'),
'skills' => $this->input->post('skills'),
'fulldate' => $this->input->post('daterange'),
'location' => $this->input->post('location'),
'city' => $this->input->post('sublocality_level_1'),
'capital' => $this->input->post('locality')
);
if (!empty($filterdata['interests'])) {
$filterdata['interests'] = rtrim($filterdata['interests'], ";");
$filterdata['interests'] = str_replace(' ', '', $filterdata['interests']);
$filterdata['interests'] = str_replace(';', ',', $filterdata['interests']);
}
if (!empty($filterdata['skills'])) {
$filterdata['skills'] = str_replace(' ', '', $filterdata['skills']);
$filterdata['skills'] = explode(",", $filterdata['skills']);
}
//Manually clear the commune and city variables if the location was empty
if (empty($filterdata['location'])) {
$filterdata['city'] = '';
$filterdata['capital'] = '';
}
if($city == null){
$orgId = $this->organization_model->getOrgIdByName(LOCATION);
}
else{
$orgId = $this->organization_model->getOrgIdByName($city);
$data['bread'] = $this->breadcrumbmanager->getLocalBreadcrumb($this->namemanager->getDashboardBreadName("0"), $city, $data['title'], $data['vacancydetails']);
}
//Set the location to the subdomain automatically (e.g. when the link is clicked) so the activities of that subdomain only show up
if (!empty(LOCATION)) {
$data['title'] = sprintf(lang('page_title_local_activities'), ucwords(LOCATION));
$data['description'] = sprintf(lang('meta_desc_local_activities'), ucwords(LOCATION));
$filterdata['location'] = LOCATION;
$data['bgcolor'] = $this->localSettings_model->getBgColorHexValueForOrgId($orgId->org_id);
}
if (!empty($filterdata['fulldate'])) {
$splitfromandto = explode(" - ", $filterdata['fulldate']);
$filterdata['datefrom'] = $splitfromandto[0];
$filterdata['dateto'] = $splitfromandto[1];
} else {
$filterdata['datefrom'] = null;
$filterdata['dateto'] = null;
}
//Put these variables in the data variable so we can prefill our filters again with the previous values
//This is necessary because we don't use AJAX yet
$data['filterdata'] = $filterdata;
//Pagination : We do it here so we can re-use the filter query to count all our results
$this->load->library('pagination');
$data['all_vacancies'] = $this->vacancies_model->getFilteredVacancies($filterdata);
$pagconfig['base_url'] = base_url().VACANCY_OVERVIEW;
$pagconfig['total_rows'] = count($data['all_vacancies']);
$pagconfig['per_page'] = 1;
$pagconfig['uri_segment'] = 2;
$pagconfig['use_page_numbers'] = TRUE;
$this->pagination->initialize($pagconfig);
$data['links'] = $this->pagination->create_links();
$start = max(0, ( $this->uri->segment(2) -1 ) * $pagconfig['per_page']);
//This variable contains all the data necessary for a vacancy to be displayed on the vacancy overview page
$data['vacancies'] = $this->vacancies_model->getFilteredVacancies($filterdata, false, null, false, null, false, false, $pagconfig['per_page'], $start);
// Template declaration
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => 'dashboard/vacancy/overview', 'footer' => '_master/footer/footer');
$data['vacancygrid'] = $this->load->view('dashboard/vacancy/vacancygrid', $data, TRUE);
$this->template->load('_master/master', $partials, $data);
}
As you can see in the code i keep a variable called $filterdata, this contains all data which is used in our filters, since we don't use AJAX in this version, we need to pass it to the view every time to fill it up again and present it to the visitor.
However, using pagination this breaks because it just reloads my controller method and thus the values in $filterdata are lost.
How do I go about this?
Note: it does not have to be a clean solution, it just needs to work since this page is going offline in a couple of weeks anyway.
Thanks a lot in advance!

PHP Arrays Selection from URL

I have coded a internal messenger system for the company I work for and I am trying to make things easier for myself by making a admin panel for this so it can control the usernames, passwords and groups.
Basically I am trying to select a user from the array using a url ?user=username which will then return the user information and allow it to be changed. The problem I am having is to get the url to select the username in the array.
The array is basic:
$users = array(
'0' => array(
'username' => 'test',
'password' => 'test123',
'group' => 'office',
),
Like this?:
<?php
// get username from URL (GET METHOD)
$username=$_GET["username"];
// $users has all the info
foreach ($users as $u) {
// find the target user
if ($u["username"] == $username) {
// do something with $u
var_dump($u);
}
}
?>
Did you tried to do this:
$user_name = $users[0]["username"];
Try this (not tested)
$u = null;
foreach($user as $user) {
if(isset($_GET['user']) && $user['username'] == $_GET['user']) {
$u = $user;
}
}
$u variable should contains yours user record.
Since it's an array i assume you have multiple indexes. I guess a simple 'find' function might work.
function findUser($searchData, $users, $searchField) {
$retObj = array();
foreach ($users as $user) {
if (isset($user[$searchField]) && $user[$searchField] == $searchData) {
$retObj['username'] = $user['username'];
$retObj['password'] = $user['password'];
$retObj['group'] = $user['group'];
break;
}
}
return $retObj;
}
EDIT: Added searchField so u can do same for password and group. Searchdata is the value u are searching

Login with User-Agent as token

I'm working on a website project (PHP, Fat-Free and mongodb) and I have a problem with only one user.
When the user does login, I call this function:
function login() {
$user = F3::get('POST.user');
$pass = F3::get('POST.pass');
if($user!=""&&$pass!=""){
$bcrypt = new Bcrypt(12);
$ismail = strrpos($user, "#");
$loginUser = new HT('user');
if($ismail===false){
$loginUser->load(array('nick' => $user));
}else{
$loginUser->load(array('email' => strtolower($user)));
}
if(!$loginUser->dry()){
if($loginUser->isActive == true){
$isValid = $bcrypt->verify($pass, $loginUser->password);
if($isValid){
$final_token = StringHelper::rand_str(30);
$tmp = $loginUser->token;
if(!is_array($tmp))
$tmp = array();
$cli_id = md5($_SERVER['HTTP_USER_AGENT']);
$tmp[$cli_id] = $final_token;
$loginUser->token = $tmp;
$user_id = $loginUser->_id."";
$loginUser->loginDate = new MongoDate();
$loginUser->updateFromId();
$isPremium = $loginUser->isPremium;
F3::set('user_id', $user_id);
if(isset($loginUser->preferences) && isset($loginUser->preferences['langPref'])){
$lang = $loginUser->preferences['langPref'];
echo json_encode(array("status"=>"OK","id"=>"$user_id","token"=>"$final_token","langPref"=>"$lang","schema"=>"$schema","isPremium"=>$isPremium));
}else{
echo json_encode(array("status"=>"OK","id"=>"$user_id","token"=>"$final_token","langPref"=>"en","schema"=>"$schema","isPremium"=>$isPremium));
}
}else{
echo json_encode(array("status"=>self::NOT_EXIST));
}
}else{
echo json_encode(array("status"=>self::NOT_ACTIVE));
}
}else{
echo json_encode(array("status"=>self::NOT_EXIST));
}
}
}
NOTE: dry() function checks if user is null in mongodb.
The user says that in his office computer can't do login, and he gets and "Invalid password" error. But he can login in the website in any other computer.
Sometimes, if he deletes cache or reset his password can access to the website.
I'm saving in the 'User' mongodb collection an array of tokens like this:
{
........ (Other params),
"token" : {
"d222b6a854d35c9c9584e695b623c468" : "nX0CuAraUQMGm5UsUWhUqZzgXZnapN",
"8c27b0d66a7ea6cec5dda9979cc92bd3" : "swdYhSQN5el0x9Pmn2YXZuwckpmuHP",
"28b825f204e7ebd320756bd6294a29c1" : "UFGd18db8W9gq1WDXgx4F9BZRVRY3K"
}
}
This token array contains:
key: MD5 encrypted User-Agent
value: Random string
This keeps session for different devices and browsers.
Everytime the user wants to do something in the web I put in the route the user id and the token (value), and I check if values are correct:
....
$uid = md5($_SERVER['HTTP_USER_AGENT']);
if(isset($user->token[$uid]) && $user->token[$uid]==$token){
....
return true;
}else{
return false;
}
I thought that the problem was with the User-Agent. Any solution?
Thanks!

Assigning gid to new user in joomla 1.5

I've created several new child groups under registered users and when I create a new user from the backend, everything works fine. When trying to create an account on the frontend the system is giving them the gid of the parent group (registered users). I would like to know if you can pass the gid to joomla. Here's the script I'm using that's not working. Many thanks!
// Begin create user
global $mainframe;
JFactory::getLanguage()->load('com_user');
$this->execPieceByName('ff_InitLib');
$user = clone(JFactory::getUser());
$pathway =& $mainframe->getPathway();
$config =& JFactory::getConfig();
$authorize =& JFactory::getACL();
$document =& JFactory::getDocument();
// If user registration is not allowed, show 403 not authorized.
$usersConfig = &JComponentHelper::getParams( 'com_users' );
if ($usersConfig->get('allowUserRegistration') == '0') {
echo '<script>alert("Access forbidden");history.go(-1);</script>';
return;
} else {
// Initialize new usertype setting
$newUsertype = $usersConfig->get( 'new_usertype' );
if (!$newUsertype) {
$newUsertype = 'Free User';
}
// Bind the post array to the user object
$post = array(
'name' => ff_getSubmit('ownerName'),
'username' => ff_getSubmit('ownerEmail'),
'email' => ff_getSubmit('ownerEmail'),
'password' => ff_getSubmit('password'),
'password2' => ff_getSubmit('password'),
'task' => 'register_save',
'id' => '0',
'gid' => ff_getSubmit('101'),
);
if (!$user->bind( $post, 'usertype' )) {
echo '<script>alert("'.addslashes($user- >getError()).'");history.go(-1);</script>';
return;
} else {
// Set some initial user values
$user->set('id', 0);
$user->set('usertype', 'Free User');
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
$date =& JFactory::getDate();
$user->set('registerDate', $date->toMySQL());
// If user activation is turned on, we need to set the activation information
$useractivation = $usersConfig->get( 'useractivation' );
if ($useractivation == '1')
{
jimport('joomla.user.helper');
$user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
}
// If there was an error with registration, set the message and display form
if ( !$user->save() )
{
echo '<script>alert("'.addslashes(JText::_( $user->getError())).'");history.go(-1);</script>';
return;
} else {
$db =& JFactory::getDBO();
$name = $user->get('name');
$email = $user->get('email');
$username = $user->get('username');
JFactory::getDBO()->setQuery("Update #__facileforms_records Set user_id = '".$user->get('id')."',
username = ".JFactory::getDBO()->Quote($username).", user_full_name = ".JFactory::getDBO()->Quote($name)." Where id = '".$this->record_id."'");
JFactory::getDBO()->query();
}
}
}
[SOLVED] Assigning gid to new user in joomla 1.5
I figured it out. If anyone else looking for an answer to this questions, just replace this line of code:
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
with
$user->set('gid', 'your gid#);

Categories