Showing posts with label session. Show all posts
Showing posts with label session. Show all posts

Saturday, July 22, 2017

Laravel 5 : Get Session Value | Another Session Value | Another Session Instance | Session Instance | HTTP Session | Session Mock | Mock Session | Duplicate Session | SessionManager | StartSession | Session Config | Get Session Config

Laravel 5 : Get Session Value | Another Session Value | Another Session Instance | Session Instance | HTTP Session | Session Mock | Mock Session | Duplicate Session | SessionManager | StartSession | Session Config | Get Session Config.


$sm = app("\\Illuminate\\Session\\SessionManager");
print_r($sm->getSessionConfig());

$sm = new \Illuminate\Session\SessionManager(app());
$ss = new \Illuminate\Session\Middleware\StartSession($sm);
$rq = \Illuminate\Http\Request::create("/", 'GET', array());
$ts = $ss->getSession($rq);
$ts->setId("7fe8a41c8185ef91e1c2b6aaab547ff34f2fed33");
$ts->start();
$ts->set("x", "value of x");
$ts->save();
print_r($ts->all());

And output below:


Array
(
    [driver] => file
    [lifetime] => 1440
    [expire_on_close] => 
    [encrypt] => 
    [files] => ...\project\storage\framework/sessions
    [connection] => 
    [table] => sessions
    [lottery] => Array
        (
            [0] => 2
            [1] => 100
        )

    [cookie] => laravel_session
    [path] => /
    [domain] => 
    [secure] => 
)
Array
(
    [_token] => Bm0Gu0lfy9JVI9TyQnddZVxBe3wndiiUR2NkDd9P
    [url] => Array
        (
        )

    [_previous] => Array
        (
            [url] => http://my_domain.com
        )

    [flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d] => 371
    [tz] => Asia/Dhaka
    [Hi] => Hello
)

Laravel 5 Session: Use Multiple Session Same Request | Duplicate Session | Use Value Of Another Session | Value From Another Session | PHP Raw Session

Laravel 5 Session: Use Multiple Session Same Request | Duplicate Session | Use Value Of Another Session | Value From Another Session | PHP Raw Session.


$session = new \Symfony\Component\HttpFoundation\Session\Session();
$session->setId("b858d2e0f84942ea2a3bb34bf2aa2a176f06b0c6");
$session->start();

$session->set("updated_time", date("Y-m-d H:i:s"));
$session->save();

echo session()->getId();
echo "<BR>";
print_r($session->all());

You can set Laravel default session save path using below example:



public function test(\Illuminate\Config\Repository $config)
{
    session_save_path($config->get("session.files"));
    $session = new \Symfony\Component\HttpFoundation\Session\Session();
    $session->setId("b858d2e0f84942ea2a3bb34bf2aa2a176f06b0c6");
    $session->start();

    $session->set("updated_time", date("Y-m-d H:i:s"));
    $session->save();

    echo session()->getId();
    echo "<BR>";
    print_r($session->all());
}

PHP Session: Use Multiple Session Same Request | Duplicate Session | Use Value Of Another Session | Value From Another Session

PHP Session: Use Multiple Session Same Request | Duplicate Session | Use Value Of Another Session | Value From Another Session.


<?php
$path = ini_get('session.save_path');
session_start();
$id = session_id();
$_SESSION["name"] = isset($_GET["name"]) ? $_GET["name"] : "No Name";
$_SESSION["tokens"] = array();
echo "<pre>";
echo "Session Save Path: " . $path . ",Session_id=$id\r\n\r\n";
willThisWork();
echo "\r\nORIGINAL_SESSION\r\n";
print_r($_SESSION);

function willThisWork() {
    $existing = session_id();
    session_write_close();

    ob_start();
    session_id("MyCommonSessionInstance");
    session_start();
    if (!isset($_SESSION["tokens"])) {
        $_SESSION["tokens"] = array();
    }
    for ($i = 0; $i < 10000; $i++) {
        array_push($_SESSION["tokens"], md5(time().rand(9999,999999)));
    }
    $start = microtime(true);
    if (count($_SESSION["tokens"]) > 100000) {
        $_SESSION["tokens"] = array_slice($_SESSION["tokens"], 75000);
    }
    $in_array = count($_SESSION["tokens"]).",EXISTS=" . (in_array($_SESSION["tokens"][count($_SESSION["tokens"]) - 1], $_SESSION["tokens"]));
    session_write_close();
    ob_get_clean();
    echo("TIME_TAKE=" . ((microtime(true) - $start) / 1000))." ms\r\n";


    session_id($existing);
    session_start();
    echo "COUNT=$in_array\r\n";
}
echo "</pre>";

And output is below:

Session Save Path: C:\xampp\tmp,Session_id=crolfji99hva2o0dflkg4ddj93

TIME_TAKE=1.2001037597656E-5 ms
COUNT=65000,EXISTS=1

ORIGINAL_SESSION
Array
(
    [name] => No Name
    [tokens] => Array
        (
        )

)

Friday, June 16, 2017

Laravel 5.X: Access HTTP Session From Controller | Service

It's very important to have access to HTTP session in our Laravel Controller or Service class. Below is a code sample of session access in Controller class. Use of session in Service is similar.


<?php

namespace App\Http\Controllers;

use Symfony\Component\HttpFoundation\Session\Session;

class HomeController extends BaseController
{
    private $Session;
    public function __construct(Session $Session)
    {
        $this->Session = $Session;
    }

    public function setSessionValue()
    {
        $this->Session->set("some_name", "some_value_in_session");
        exit;
    }

    public function getSessionValue() {
        echo $this->Session->get("some_name");
        die();
    }










Wednesday, December 18, 2013

Grails access HttpSession from service or from other src files


import org.springframework.web.context.request.RequestContextHolder; 
HttpSession session = RequestContextHolder.currentRequestAttributes().getSession();

##### 
/* Code */
session.properties.each {
    println it;
}

/* Output from above code */
creationTime=1387331940863
maxInactiveInterval=1800
sessionContext=org.apache.catalina.session.StandardSessionContext@1ff04376
attributeNames=java.util.Collections$2@2aec16fa
class=class org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession
servletContext=org.apache.catalina.core.ApplicationContextFacade@3dc6e9f8
new=false
id=A2791167D1EC3D21025078895357147D
valueNames=[Ljava.lang.String;@71d88d19
lastAccessedTime=1387332146960

#####
/* Code */
session.attributeNames.each {
    println it;
}

/* Output from above code */
SETTING
org.codehaus.groovy.grails.FLASH_SCOPE
USER

#####
/* Code */
session.attributeNames.each {
    println session.getAttribute(it.toString());
}

/* Output from above code */
[paginationCount:10, generateClientID:On]
[:]
[name:Admin, id:1, username:admin, isSystemAdmin:true]

Wednesday, October 23, 2013

Duplicated records/data persistence/flush session error with Grails in synchronized method

Consider some of cases: 

  1. When domain fails to save data because of duplicate record.
  2. When an unsaved domain belongsTo a domain, then showing: 'save the transient instance before flushing'.
Then  - Domain.save(flush:true) - didn't work because of threading.
Here is example of my thread creation:
Thread.start {
    Domain.withTransaction {
         // Doing stuff and calling synchronization method to write data to DB
    }
}
Fix was found here: Grails, GPars and data persistence
I replaced "Domain.withTransaction" with "Domain.withNewSession":
Thread.start {
    Domain.withNewSession {
         // Doing stuff and calling synchronization method to write data to DB
    }
}
and save(flush:true) start writing into mySQL. Since data is written to mySQL, findBy... start returning proper results and therefore I application doesn't try to create duplicated record anymore. Issue solved!

Wednesday, October 2, 2013

Grails Hibernate - null id in entry (don't flush the Session after an exception occurs)

I ran into this issue today when trying to persist one of my objects.  The cause of the problem was interesting.  I was trying to save an object when a property/columns in the table had a unique constraint.  As a result, the object that I was trying to persist would not persist simply because the object's property it failed to meet the unique constraint.

As a result, a call to Save() on the object failed and the ID on the object I was trying to save was not set, but Grails Hibernate still processed the object and associated it with its persistence mechanism leaving it in a "semi-persistent" state with the Grails Hibernate persistence manager (ie: Grails Hibernate now knows about the object you tried to save and it SHOULD have fully evicted the object from its persistence manager because the save failed, but it didn't).

So, the solution that I implemented was to wrap the Save() in a try{} catch{} statement and handling exception.

Basically you need to do something like this:
Create a Filters in conf directory under grails project suppose named 'BaseFilters.groovy' with the following content:
 
import org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext
import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.hibernate.FlushMode
import org.hibernate.Session
import org.hibernate.SessionFactory

class BaseFilters {
    private static GrailsWebApplicationContext ctx;

    def filters = {
        all(controller:'*', action:'*') {
            before = {
                Session session = getRequestSession();
                session.setFlushMode(FlushMode.MANUAL)
                request.requestSession = session;
            }
            after = { Map model ->
                try {
                    Session session = request.requestSession;
                    session.flush();
                } catch (Exception ex) {
                    ex.printStackTrace()
                }
            }
            afterView = { Exception e ->

            }
        }
    }

    private Session getRequestSession() {
        createCtx();
        SessionFactory sessionFactory = ctx.sessionFactory
        Session session = sessionFactory.currentSession
        return session;
    }

    private def createCtx() {
        if(!ctx) {
            ctx = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
        }
    }
}

Originally session flush mode initially set to 'FlushMode.AUTO' which cause the error.
So I change the session flush mode to 'FlushMode' to 'MANUAL'.
And also make your service transaction false such: static transactional = false, add this line just below the class definition.

And in the after section, I just manually try to flush, which is not much needed, you can ignore it.
I just add this section to do some logic manually if need.

Friday, June 21, 2013

Encrypted Sessions with PHP

Here's the code, an explanation will follow:



<?php
class Session
{
    /**
     * Path to save the sessions to
     * @var string
     */
    private $savePathRoot = '/tmp';

    /**
     * Save path of the saved path
     * @var string
     */
    private $savePath = '';

    /**
     * Salt for hashing the session data
     * @var string
     */
    private $key = '282edfcf5073666f3a7ceaa5e748cf8128bd53359b6d8269ba2450404face0ac';

    /**
     * Init the object, set up the session config handling
     *
     * @return null
     */
    public function __construct()
    {
        session_set_save_handler(
            array($this, "open"), array($this, "close"),  array($this, "read"),
            array($this, "write"),array($this, "destroy"),array($this, "gc")
        );

        $this->savePathRoot = ini_get('session.save_path');
    }

    /**
     * Encrypt the given data
     *
     * @param mixed $data Session data to encrypt
     * @return mixed $data Encrypted data
     */
    private function encrypt($data)
    {
        $ivSize  = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $iv      = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $key     = substr(sha1($this->key), 0, $keySize);

        // add in our IV and base64 encode the data
        $data    = base64_encode(
            $iv.mcrypt_encrypt(
                MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv
            )
        );
        return $data;
    }

    /**
     * Decrypt the given session data
     *
     * @param mixed $data Data to decrypt
     * @return $data Decrypted data
     */
    private function decrypt($data)
    {
        $data    = base64_decode($data, true);

        $ivSize  = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $key     = substr(sha1($this->key), 0, $keySize);

        $iv   = substr($data, 0, $ivSize);
        $data = substr($data, $ivSize);

        $data = mcrypt_decrypt(
            MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv
        );

        return $data;
    }

    /**
     * Set the key for the session encryption to use (default is set)
     *
     * @param string $key Key string
     * @return null
     */
    public function setKey($key)
    {
        $this->key = $key;
    }

    /**
     * Write to the session
     *
     * @param integer $id   Session ID
     * @param mixed   $data Data to write to the log
     * @return null
     */
    public function write($id, $data)
    {
        $path = $this->savePathRoot.'/'.$id;
        $data = $this->encrypt($data);

        file_put_contents($path, $data);
    }

    /**
     * Read in the session
     *
     * @param string $id Session ID
     * @return null
     */
    public function read($id)
    {
        $path = $this->savePathRoot.'/'.$id;
        $data = null;

        if (is_file($path)) {
            // get the data and extract the IV
            $data = file_get_contents($path);
            $data = $this->decrypt($data);
        }
        return $data;
    }

    /**
     * Open the session
     *
     * @param string $savePath  Path to save the session file locally
     * @param string $sessionId Session ID
     * @return null
     */
    public function open($savePath, $sessionId)
    {
        // open session, do nothing by default
    }

    /**
     * Close the session
     *
     * @return boolean Default return (true)
     */
    public function close()
    {
        return true;
    }

    /**
     * Perform garbage collection on the session
     *
     * @param int $maxlifetime Lifetime in seconds
     * @return null
     */
    public function gc($maxlifetime)
    {
        $path = $this->savePathRoot.'/*';

        foreach (glob($path) as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }

    /**
     * Destroy the session
     *
     * @param string $id Session ID
     * @return null
     */
    public function destroy($id)
    {
        $path = $this->savePathRoot.'/'.$id;
        if (is_file($path)) {
            unlink($path);
        }
        return true;
    }
}
?>

Resources

Php Session ID, Session Save Path, Session List

ini_set('session.save_path', "C:\temp_sessions");
session_id(md5("".time())); /* every time set new session id */
//ini_set('session.gc_probability', 1); /* To remove previous sessions */
session_start();

echo session_id();
echo session_save_path();
echo "Session Save Path: " . ini_get( 'session.save_path');
$sessions = array();

$path = realpath(session_save_path());
$files = array_diff(scandir($path), array('.', '..'));

foreach ($files as $file)
{
    if(is_file($path.DS.$file) ) {
        $content = file_get_contents($path.DS.$file);
        $sessions[$file] = $path."/".$file;
        $sessions[$file."_content"] = unserialize($content);
    }
}

$path = session_save_path()."/*";

foreach (glob($path) as $file) {
    $diff = time() - filemtime($file);
    echo $file.", Last Updated= ".filemtime($file)."   ,Difference=   ".$diff."<br/>";
}