Save complete model in session - Codeigniter - codeigniter

I want to save complete model in session, so I can use data easily in entire application.
After successful login in application I am saving model in session and session save in database in ci_session table.
Code I tried:
$loginSuccess = $this->login_model->doLogin($username, $password);
if($loginSuccess) {
$this->login_model->initialize(); // this will set value in private variable
$serializelogin = serialize($this->login_model);
$this->session->set_userdata('userprofile', $serializelogin);
}
This code gives me an error:
Error Number: 2006
MySQL server has gone away
Update: I change user_data column of table ci_session from text to longtext

U need to start by creating a session.
//Destroy old session
$this->session->sess_destroy();
//Create a fresh, brand new session
$this->session->sess_create();
//Set session data
$this->session->set_userdata($row);
Basically $row is an array.
$row = $serializelogin->row_array();
or
$this->session->set_userdata(array('active_flag' => false, 'active_status' => 0));
make sure the data which has been returned from the model is in row_array format.

Related

how to session()->forget('cart') for another user in laravel?

my session driver is set to database,
.env => SESSION_DRIVER=database
I have made a model for session and I access to a session of another user by user_id like this :
use App\Models\Session;
$payload = Session::where('user_id', $request->user_id)->pluck('payload');
$payload = unserialize(base64_decode($payload));
if (!isset($payload['cart'])) {
dd($payload['cart']);
}
now I want to session()->forget('cart') of that specific user not the current user, but the payload field is decode by base64 and serialized.
how to do that?
thanks
I tried a few things and by changing the id it works :
// Get the store from laravel (encrypted or not)
$store = session()->getDrivers()['database'];
// Change the id
$store->setId($id);
// Start the session
$store->start();
// Remove the item
$store->pull('cart');
// Save the session in database
$store->save();
i don't think it's something that laravel support, so this might break in the future
Yes I found it.
the problem is to displacement of serialize() and base64_encode() after unset($payload['cart']) like this:
use App\Models\Session;
$session = Session::where('user_id', $request->user_id)->first();
$payload = unserialize(base64_decode($session->payload));
if (!isset($payload['cart'])){
unset($payload['cart']);
}
$session->payload = base64_encode(serialize($payload));
$session->save();

I am getting an error message on my laravel app: creating default object from empty value

I want to save some values in my transaction table. I stored the value of the pharmacy in a session and now am trying to save it. This is my controller;
Public function redirectToGateway(Request $request)
{
$old cart= Session:: get('cart');
$cart=new Cart($oldCart);
session ()->put ('user_id,$request->get('user_id));
session ()->put ('pharmacy',$request->get('pharmacy'));
$id= Session:: get('user_id');
$pharmacy= Session:: get('pharmacy');
$transhistory=Transaction:: find($id);
$transhistory->pharmacy=pharmacy;
$transhistory->email=$request->get('email');
$transhistory->amount=$request->get('amount');
$transhistory->cart=serialize($cart);
$transhistory->save();
First check if the session values really exists or not and secondly this $transhistory->pharmacy=pharmacy; should be $transhistory->pharmacy=$pharmacy;

How to Check if Session is set in Laravel 5.7

<?php
$request = request();
// if (empty($request)) return false; .// That does not work
$loggedUserAccessGroups = $request->session()->get('loggedUserAccessGroups');
$logged_user_ip = $request->session()->get('logged_user_ip');
In my Laravel 5.7 application, I want to check if the user has the right access level in the session. It works ok but I made automatic tests and got the error:
local.ERROR: Session store not set on request.
I added checks to see if the session is set and it fails to return false.
Which is the correct way? Thanks!
You may also use the global session PHP function to retrieve and store data in the session as outlined here:
// Retrieve a piece of data from the session with the global session helper...
$loggedUserAccessGroups = session('loggedUserAccessGroups');
$logged_user_ip = session('logged_user_ip');
// Store a piece of data in the session...
session(['key' => 'value']);
For more information look at the section of The Global Session Helper in the official documentation.

Send Data From html5 app to database by ajax and php

i have start a new application html5 and i need to send from that app the info user_points to the database i have the code that send a fixed amount points.
But Now I need to change the php code to receive ajax request to update is points on database From My html5 app.
what i can change to this php code to receive the ajax variable user_points and store in database?
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
// Retrieve data from database
$result=mysql_query($sql);
//$sql = mysql_query("UPDATE `users` SET points=`points`+5 WHERE user_id='".$_SESSION['user']."'");
$user_id = mysql_real_escape_string($_SESSION['user']);
$sql = mysql_query("UPDATE `users` SET user_points = user_points +'user_points' WHERE user_id = " . $_SESSION['user']);
// close MySQL connection
mysql_close();
?>
assume your php script is called run.php
and assume run.php is called via ajax like this http://yourserver/run.php?user_points=10&userid=12&sessiontan=8162836zqwizß182402834080oio
your script run.php would need to look like this:
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_GET['userid']) and isset($_GET['user_points'] and isset($_GET['sessionpin']))) {
$res=mysql_query("SELECT userid FROM sessiontans WHERE user_id=x".dechex($_GET['userid'])" and sessiontan=x".dechex($_GET['sessiontan']));
if($row = mysql_fetch_array($res)) {
$sql = mysql_query("UPDATE `users` SET user_points = user_points + x".dechex($_GET['user_points'])." WHERE user_id = x" . dechex($_GET['userid']));
}
}
// close MySQL connection
mysql_close();
?>
As far as I am aware the session context is not available in ajax called scripts. So security wise that needs to 'simulated' via sessiontans or similar mechanisms. I assumed now, you would follow a sessiontan approach. A session tan be created in your app as soon as the user logs and is via time stamps only valid for a tiny time frame (a couple of minutes/hours). A sessiontan would need to be different from session-IDs.
I personally would add more sophisticated checks on the user-points to make sure that the those are not tricked... Anyway that is more on the 'game logic' side and would require a lot more insight on what this is all about.
Also in terms of performance tuning both statements could become part of a multi query: http://php.net/manual/de/mysqli.multi-query.php
Again this is advanced programming tactics and superexceeds the scope of your question.

fatfree sessions, different values in database and echo stmt

I have this in my beforeroute() of a controller
public function beforeroute()
{
new \DB\SQL\Session($this->db);
$mapper = new \DB\SQL\Mapper($this->db, 'users');
$auth = new \Auth($mapper, array(
'id' => 'username',
'pw' => 'password'
));
if (!$auth->login('validuser', '1234')) {
die('username or password wrong');
} else {
echo ($csrf = $this->db->exec('SELECT csrf FROM sessions')[0]['csrf']);
}
}
After I hit the page, I have different values for csrf in database and what's been echoed out on page. Why is that?
The csrf token is renewed on every request. You see different values on the page and in the database, because the value in the database was updated after your page has rendered.
To be more specific, the SQL Session handler replaces the default php session handler, and that's why the call to session_commit within the unload method https://github.com/bcosca/fatfree-core/blob/master/base.php#L1903 (is called when the framework shut down) will update your session database table with the new value.
To have a way to reuse that single csrf token for your purpose, just put it back into the session itself:
$s = new \DB\SQL\Session($f3->get('DB'));
// old value from last request
echo $f3->get('SESSION.csrf');
// remember current value for next request
$f3->set('SESSION.csrf',$s->csrf());
Maybe there`s an easier way, but I haven't figured it out yet.

Resources