Sessions in Codeigniter with PHP7 - codeigniter

The Problem is simple. If i use
$this->session->sess_destroy();
$this->session->sess_regenerate(true);
i get an error:
Message: session_regenerate_id(): Cannot regenerate session id - session is not active
Filename: Session/Session.php
Line Number: 625
That only happens with PHP 7 and works with 5.6.
I figured that the parameter in the regenerate function is set to destroy the old session data when regenerating. When i leave out the sess_destroy() i don't get an error, but the session data is not destroyed and i can't log the user out.

Use ob_start() before session library. And before session destroying code add ob_flush() and after that line set ob_clean()
And set this $this->session->sess_regenerate(true); to FALSE. ob_flush and ob_clean will do that perfectly.

Related

unserialize(): Error at offset 0 of 40 bytes Error

I Want to run my application in localhost with php artisan serve but I get this Error unserialize(): Error at offset 0 of 40 bytes where is my problem?
You have to set a news Key Generate because
php artisan key:generate
After that test again to run the Laravel Application
php artisan serve
I got the same error, when I upgrade a Laravel 5.5 app to 5.6. The error comes form the EncryptCookies-Middleware.
Delete the cookies in your browser and/or clear your session-files in your Laravel app.
I've faced same problem. I frequently faced this problem in Homestead-vagrant environment.
To solve this issue in Laravel 5.4,5.5,5.6 or more -
php artisan config:clear
php artisan view:clear
php artisan key:generate
I got the same error a couple of days ago when I pushed a production update to my Laravel project from Envoyer.
Immediate fix:
I tried to rollback to the previous commit but the issue persisted which means the issue was originating from the client side, cookies probably. I tried removing cookies and the issue was gone.
Later, I spent a lot of time looking for this issue but got nothing until I faced this issue again today with another deployment and i found this article on Laravel news about the security fix 5.6.30 update. I was able to identify that this issue occurs if i try to deploy previous (< 5.6.30) version of the laravel v5.6.26 for a project which was already using > v5.6.30 and cookies were already created ( not serliazed) which when <5.6.30 version of the framework tries to unserlize results in error because they're not properly serealized.
Installing laravel/framework (v5.6.26)
Loading from cache
From the upgrade guide:
Configuring Cookie Serialization Since this vulnerability is not able
to be exploited without access to your application's encryption key,
we have chosen to provide a way to re-enable encrypted cookie
serialization while you make your application compatible with these
changes. To enable / disable cookie serialization, you may change the
static serialize property of the App\Http\Middleware\EncryptCookies
middleware:
I was able to fix this issue permanently by clearing cache of composer so forcing it to load latest version of the framework instead of falling back to cache.
Hope this helps.
Bests,
Just Inspect the element in Browser, and go to application tab and select cookie and delete that all cookie. That's It.
In App\Exceptions\Handler under render function use this snippet, it will reset browser cookie.
if (str_contains($exception->getMessage(), 'unserialize')) {
$cookie1 = \Cookie::forget('laravel_session');
$cookie2 = \Cookie::forget('XSRF-TOKEN');
return redirect()->to('/')
->withCookie($cookie1)
->withCookie($cookie2);
}
In my case I did removed my composer.lock and did a composer install and voila...
$ cd project_root
$ rm composer.lock
$ composer install
I also encountered this issue when I happened to update my composer.
If you put
protected static $serialize = true;
inside App\Http\Middleware\EncryptCookies, the old cookie will break your system. So to prevent this, either you have to clear the cookie, or just don't unserialize the decrypted cookie.
I made a workaround for this:
Inside vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php
Above this line of decrypt() function:
return $unserialize ? unserialize($decrypted) : $decrypted;
add:
try {
return $unserialize ? unserialize($decrypted) : $decrypted;
} catch (\Exception $e){
return $decrypted;
}
This might be ugly, but you can temporarily put it there until you think the old cookies has gone.
In my case, I was trying to decrypt a hash with an wrong function.
I was creating encrypt using encryptString()
$hash = Crypt::encryptString('secret');
but I tried to decrypt using decrypt()
$value = Crypt::decrypt($hash);
the correct way is
$value = Crypt::decryptString($hash);
So when you encrypt using Crypt::encrypt() you must decrypt it using Crypt::decrypt(), and for Crypt::encryptString() use Crypt::decryptString()
The first thing you should do is clear the configuration cache file
php artisan config:clear
Then create a new key for the application
php artisan key:generate
Finally, restart the server.. I hope it will fix your problem.
In my case happened during local development.
The steps that caused the problem was:
I upgraded the laravel up to 5.8 on a seperate branch.
I switched into an another branch having laravel 5.2 (in my case I had to review a PR)
I also was logged in in my app and hence there was a session cookie as well. In that case I just cleared the browser's cookies and got fresh ones.
In firefox can be done via visiting then select about:preferences#privacy and select the appropriate option. as the following images show (in Greek)
Privacy setting and an indication where the user to click
An anothwer aproach to diagnose the issue it to open a private firefox window or use chrome's cognito mode.
yeah, for localhost you can just delete cookies, but for production put this in your error handler so users would not see whoops :
if (strpos($exception->getMessage(), 'unserialize(): Error at offset 0 of 40 bytes') === 0) {
unset($_COOKIE['laravel_session']);
unset($_COOKIE['XSRF-TOKEN']);
setcookie('laravel_session', null, -1, '/');
setcookie('XSRF-TOKEN', null, -1, '/');
abort(200, '', ['Location' => route('frontend.home')]);
}
PS. tested for laravel 5.6.
you will just run in terminal
composer global update

Laravel Socialite InvalidStateException in AbstractProvider.php line 200

I'm building a web app in my local system (Ubuntu-14.04 64Bit) using laravel 5.3. I used Socialite to signin from social networks. I configured G+, Facebook, GitHug. I'm using Chromium as my default browser. Finally the problem is i'm getting
InvalidStateException in AbstractProvider.php line 200
frequently. i tried
php artisan cache:clear
php artisan config:clear
composer dump-autoload
these are helping to solve the issue temporarily, again the problem raising.
please help me in this issue..
I have the same issue and I've read a lot about this, that depend if the URL where you are at the moment of the login request has www. at the beginning or not.
Into config\services.php, if you have the redirect set as http://sitename.tld/callback/facebook the oauth works if you send the login request from sitename.tld, while if you try from www.sitename.tld you get the exception.
I haven't yet understood how to have it working with and without www at the beginning.
If the AbstractProvider.php line 200 fires the exception when the state of the user is not present means that the User cannot be created.
First check your code when you get the details from the provider(facebook, github) if you create a user and you return it.
If you have managed and logged in your app and you deleted the user from the user table remember to delete also the data from the socialite account table.
I was getting that exception because 'state' wasn't saved in session. But I was using asPopup method - Socialite::driver('facebook')->asPopup()->redirect(); so I saved session then - $request->session()->save();. So I solved this issue.
or try
session()->put('state', $request->input('state'));
$user = Socialite::driver('facebook')->user();
it works
I have same issue and solved in 3 steps;
add request on the top
use Illuminate\Http\Request;
Pass request object to function
public function handleProviderCallback(Request $request)
{
try {
$user = Socialite::driver('facebook')->user();
} catch (Exception $e) {
throw new Exception;
}
}
Clear cache.
php artisan cache:clear
I had the same error but my solution was a little different. I am posting here just in case someone else keeps hitting this post like I did for a possible answer.
I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.
I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.
I had set header security in my apache2 configs. One of the settings was
Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"
This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.
After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:
SESSION_SECURE_COOKIE=true
in my .env file
'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)
in my config/session.php file.
Now it is back to testing security and tweaking things back if need be.

Corrupt Kohana session after inserting a custom object

Description
I am trying to add a custom object called ReviewHolder to a session. This is being done in the "review" controller. The ReviewHolder class is included in the classes/controller/review.php file. I am using Kohana version 3.2.
The code
$session = Session::instance();
$reviewholder = $session->get('reviewholder');
if($reviewholder == null) {
$session->set('reviewholder', new ReviewHolder());
}
The problem
The problem is that after I execute the above code, the session gets corrupted and almost the entire website stops functioning correctly. This is the error message on every page:
Session_Exception [ 1 ]: Error reading session data.
The weird part
All pages that are loaded from the "review" controller are still all function correctly! It looks like the above code is messing up every other session in the application...
Debug
I have debugged the session to see if the object is set correctly with the following code:
echo Debug::vars($session->get('reviewholder'));
This shows the object correctly, so it has been set in the session.
Can someone help me out here? Thanks!
It doesn't really matter whats inside the session file.
All i know is that you can only store objects that are serialized in the session.
After serializing you can store it in an session and to make it an object again for later use. You can unserialize the serialized object.
Hope this helps!
I found the following worked for me when storing a custom object in the session:
Make sure your session directory is set correctly in PHP, ie. the directory exists, permissions allow your web server to write to the directory
Force the class for your object to be loaded in bootstrap.php by adding a line such as:
require_once( Kohana::find_file('classes','Library/MyClass') );
After those two steps I no longer saw the session corrupt exception

Symfony2 A session had already been started - ignoring session_start()

I can't use Symfony2 session in my local server. I'm getting a "Notice: A session had already been started - ignoring session_start()" error.
Same script works fine in my production server.
I'm using Xampp with PHP 5.3.5 over Windows 7. Session auto_start is off in php.ini.
Any hint will be helpfull. Thanks
I guess it's a bite late but if it can help:
Make sure your session.autostart is turned off (0) in your php.ini
The way to use the session in Symfony 2 from the controler is the following:
$session = $this->getRequest()->getSession();
// store an attribute for reuse during a later user request
$session->set('foo', 'bar');
// in another controller for another request
$foo = $session->get('foo');
// use a default value if the key doesn't exist
$filters = $session->get('filters', array());
http://symfony.com/doc/current/book/controller.html#managing-the-session
Or from the view:
{{ app.session.get('foo') }}
You should also call start() even if it is automatically called when you read/write session data (because it is recommended and getId() doesn't call it for example)
$session->start();
$id = $session->getId();
http://symfony.com/doc/master/components/http_foundation/sessions.html
The reason you may not get the error on the production server is because it's priority is 'Notice' only.

User relationships are corrupting my sessions in Symfony2

My users have a number of relationships setup in Doctrine but one in particular seems to be causing me a lot of problems, each user can have a number of memberships and each membership has a membership type.
For some reason however when I load those memberships it seems to be nuking my session, I login and get presented with a "Your Account" page as I should do but if I refresh the page I get sent back to the login screen. My sessions are stored in the database so I've been checking them to see what happens and this is what I'm seeing:
Session starts off empty
I login but make sure I get redirected to a page that doesn't load memberships
Session now contains user object and all info about relationships
I visit "Your Account" which loads memberships, they get displayed correctly.
Session has been nuked and is now as it was in step 1
I refresh the page and get sent back to the login page
I've defined my own user provider and I noticed if I set the membership type on each membership to null in refreshUser it starts working so I'm guessing the session is having trouble with that relationship.
I'm really struggling to find a solution to this so any help would be really appreciated.
EDIT: Been doing some more experimenting and found if I switch to file sessions everything starts working so it must be related to storing sessions in the database. I made the switch using the guide in the Symfony Cookbook. For reference here are the relevant bits from my config.yml:
framework:
session:
default_locale: %locale%
auto_start: true
storage_id: session.storage.pdo
parameters:
pdo.db_options:
db_table: session
db_id_col: session_id
db_data_col: session_value
db_time_col: session_time
session.storage.pdo:
class: Symfony\Component\HttpFoundation\SessionStorage\PdoSessionStorage
arguments: [#pdo, %session.storage.options%, %pdo.db_options%]
pdo:
class: PDO
arguments:
dsn: "mysql:dbname=%database_name%;host=%database_host%"
user: %database_user%
password: %database_password%
Everything else about them seems fine so maybe it's a bug in PdoSessionStorage
It might be in you equals method that is too strict. if you do $user === $otherUser; and the object have changed (the relation isnt a collection with proxies anymore) it would return false.

Resources