Can't use sessions in laravel controller

Published 1 week ago by jmar83

PHP script to check the client's IP address:

jmar83

PHP script to check the client's IP address:

jmar83

PHP script to check the client's IP address:

<?php

namespace IPv4;

if(!session_id() || session_id() == null || session_id() == '') {
    session_start();
}

require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/ipv4-subnet-calculator/src/SubnetCalculator.php";

if(true)
{
    error_reporting(E_ALL & ~E_NOTICE);
    ini_set ( 'display_startup_errors', 1 );
    ini_set ( 'display_errors', 1 );
}

// header ( "Content-Type: text/plain" );

$ipAddress = null;

if (! empty ( $_SERVER ['HTTP_CLIENT_IP'] )) {
    $ipAddress = $_SERVER ['HTTP_CLIENT_IP'];
} else {
    // echo "$_SERVER['HTTP_CLIENT_IP'] is empty...\r\n\r\n";
    if ($_SERVER ['REMOTE_ADDR'] != $_SERVER ['HTTP_X_FORWARDED_FOR']) {
        // echo "$_SERVER['REMOTE_ADDR'] is " . $_SERVER ['REMOTE_ADDR'] . "\r\n\r\n";
        $ipAddress = $_SERVER ['HTTP_X_FORWARDED_FOR'];
    }
}

// echo "$_SERVER['HTTP_X_FORWARDED_FOR'] is " . $ipAddress . "\r\n\r\n";

$range = null;
$range [0] = "www.www.www.www/a";
$range [1] = "xxx.xxx.xxx.xx/b";
$range [2] = "yyy.yyy.yyy.yyy/c";
$range [3] = "zzz.zzz.zzz.zzz/d";
class SubnetCalculatorFactory {
    public static function createInstance($ipAddress, $number) {
        return new SubnetCalculator ( $ipAddress, $number );
    }
}

$subnetCalc = null;
$ipAddressAsLong = ip2long ( $ipAddress );
function checkIPAddressIsInRange() {
    global $range;
    global $ipAddressAsLong;
    for($c = 0; $c < sizeof ( $range ); $c ++) {
        $ip = null;
        $ip_match = null;
        $text = $range [$c];
        $number = substr ( $text, - 2 );
        
        if (preg_match ( '/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $text, $ip_match )) {
            $ip = $ip_match [0];
        }
        
        $subnetCalc = SubnetCalculatorFactory::createInstance ( $ip, $number );
        $ipAddressRange = $subnetCalc->getIPAddressRange ();
        
        if (ip2long ( $ipAddressRange [0] ) <= $ipAddressAsLong && $ipAddressAsLong <= ip2long ( $ipAddressRange [1] )) {
            return 1;
        }
    }
    return 0;
}

// Use caching or not...
if(false)
{
    if(!isset($_SESSION['ipAddressIsInRange2']))
    {
        $_SESSION['ipAddressIsInRange2'] = checkIPAddressIsInRange();
    }
}
else 
{
    $_SESSION['ipAddressIsInRange2'] = checkIPAddressIsInRange();
}
?>

Application for testing its functionality:

<?php

if(true)
{
    error_reporting(E_ALL & ~E_NOTICE);
    ini_set ( 'display_startup_errors', 1 );
    ini_set ( 'display_errors', 1 );
}

require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/IPTest.php";

if(!session_id() || session_id() == null || session_id() == '') {
    session_start();
}

$test = $_SESSION['ipAddressIsInRange2'];
echo $test.", ";
die(var_dump($test));

?>

-> That test works well, when i change my IP (connect to VPN), the screen output switches from "1" to "0". (=not inside the ranges defined in array "$range")

But when i use the whole thing in a laravel session controller (together with smarty as a template engine), it does what it wants! sometime it shows "0", sometime "1":

<?php
namespace App\Http\Controllers;

if(true)
{
    error_reporting(E_ALL & ~E_NOTICE);
    ini_set ( 'display_startup_errors', 1 );
    ini_set ( 'display_errors', 1 );
}

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\DB;

require_once $_SERVER ['DOCUMENT_ROOT'].'/includes/functions.inc.php';
require_once $_SERVER ['DOCUMENT_ROOT'].'/smarty/libs/Autoloader.php';

Use \Smarty;
Use \Smarty_Autoloader;

class Index extends Controller
{
    public $smarty = null;
    
    function __construct() {
        Smarty_Autoloader::register();
        $this->smarty = new Smarty;
        $this->smarty->caching = false; // prod = true
        $this->smarty->debugging = true; // prod = false
        $this->smarty->force_compile = true; // always true, incompatible with laravel
    }
    
    public function index()
    {
        require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/IPTest.php";
        
        if(!session_id() || session_id() == null || session_id() == '') {
            session_start();
        }
        
        $url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        
        if(substr($url, -1) == '/') {
            $url = substr($url, 0, -1);
        }
        
        $content = getAllFromCMSSite("site_name2='".escape_mysql(substr($url, strrpos($url, "/") + 1))."'")[0];
        $this->smarty->assign('content', $content['site_content']);
        $this->smarty->assign('title', $content['site_name']);
        
        $this->smarty->assign('pages', getAllFromCMSSite("site_type=1"));
        $this->smarty->assign('posts', getAllFromCMSSite("site_type=2", "DESC", "5"));
        
        $this->smarty->assign('ipAddressIsInRange', $_SESSION['ipAddressIsInRange2']);
        // $this->smarty->assign('ipAddressIsInRange', 77);
        
        $html = $this->smarty->fetch($_SERVER ['DOCUMENT_ROOT']."/smarty/templates/template.htm");
        $html = compress_page($html);
        
        return $html;
    }
}

...maybe the only is to output (echo) "0" or "1" in IPTest.php and then do a HTTP request with PHP on http://www.server.com/IPTest.php, e.g. with CURL or url_fopen or whatwever..?

I use Laravel 5.4.30 with Smarty on PHP 5.6.9 on Linux together with MySQL. Nothing special in my eyes.

Regards, Jan

Cronix
Cronix
1 week ago (398,210 XP)

Why aren't you using laravels sessions? They're built in and used by default. Actually, I don't think I see a single line of laravel code anywhere in there. You're probably messing things up by using php native sessions since laravel has it's own session.

https://laravel.com/docs/5.6/session

jmar83

Because i NEED to use some legacy things. And, btw., the question was not that: "How to use the own things of laravel?"

Additional info: In the Smarty template, i use that:

´´´

{$ipAddressIsInRange}

´´´

Regards, Jan

jmar83
<p>{$ipAddressIsInRange}</p>

I want to use laravel ONLY for MVC, in combination with Smarty. (Just to have a clean structure, "skeleton" or how to call this?) The rest should be "legacy"..

Regards, Jan

Cronix
Cronix
1 week ago (398,210 XP)

And, btw., the question was not that: "How to use the own things of laravel?"

Sorry, this is a laravel forum. Most people would tell you the same since you're asking a question here and you never mentioned that you were only interested in using straight php. So, you'll probably need to figure out how to disable a lot of laravels features if you don't want to use them as they are enabled by default. Good luck!

jmar83

I never had such a crazy problem, not even with big fat J2EE frameworks on Java..;)

Java was able ~20 years ago (i think servlets and JSP's exists since ~ 1998) what Laravel does.

Laravel is young, because of that i can understand it's not very flexible.

Regards, Jan

jmar83

"not very flexible." -> "half-baked", better to say! ;)

Regards, Jan

Cronix
Cronix
1 week ago (398,210 XP)

It does great if you use it as intended, which you aren't. It's not just some tiny simple mvp framework. There are plenty of other frameworks that are more bare bones. You can badmouth it all you'd like, but you're the one who didn't investigate it or read the manual, which is kind of the obvious first step to do...

jlrdw
jlrdw
1 week ago (215,690 XP)

Are you kidding me laravel is one of the most flexible Frameworks in the world. And even regular PHP sessions work if you know what you were doing.

jmar83

"Are you kidding me laravel is one of the most flexible Frameworks in the world."

Same in my eyes. But only for the first view..

"And even regular PHP sessions work if you know what you were doing."

OK, maybe you can tell me how it works? At least i know what i WANT to do, hehe! :)

Regards, Jan

jlrdw
jlrdw
1 week ago (215,690 XP)

Look in those configuration files for session driver. And it just so happens I came from java servlets, JSP, and ejb's.

But you can use Legacy code with laravel if you understand some of the magic methods like __callStatic(), .

I recently converted a much older framework to laravel, still used old code and some controllers I custom made while converting to new code.

You also have to dig around in those API Docs.

But you can use laravel sessions with old code, make sure you put a use statement for session.

ejdelmonico

As these other folks pointed out, maybe Laravel is not the choice for you because it was written to help avoid spaghetti code like yours. I hope your controller is just a rough draft because its a giant mess. And just so you fully understand, it does not matter that you have legacy php code. A php session is always a php session. If you would explore what Laravel makes easy, you could remove most of that code. Read the docs if you care about doing it right.

jmar83

In the .env file, i see that:

CACHE_DRIVER=file SESSION_DRIVER=file

The problem seems still to persist when i avoid sessions:

$ipAddressIsInRange = checkIPAddressIsInRange();

// Use caching or not...
/*
if(false)
{
    if(!isset($_SESSION['ipAddressIsInRange2']))
    {
        $_SESSION['ipAddressIsInRange2'] = $ipAddressIsInRange;
    }
}
else 
{
    $_SESSION['ipAddressIsInRange2'] = $ipAddressIsInRange;
}
*/

Now i try to use the $ipAddressIsInRange variable (from the included IPTest PHP file) in the controller. But it does not work, still the same problem, while the test application shows the correct value. So it's not a session problem...?

Maybe laravel hides some error messages or warnings? (Maybe a OO-related problem with namespace? I don't hava a lot of experience in PHP OOP) But the log level is set to "DEBUG" in the .env file...?

Hmmmmmmmm... really strange.

Regards, Jan

jmar83

"spaghetti code like yours."

I think PHP is ideal for spaghetti code, hehe!! :)

And i also think that "pure" SQL, views, stored procedures, udf's are much more faster than the ORM things. (At least if you have billions of records!!)

My getAllFromCMSSite(...)-function is really flexible, but that's another thing.

Regards, Jan

Please sign in or create an account to participate in this conversation.