UPDATE: My issue had nothing to do with Laravel sessions, it was my Service Worker that was causing sessions to mess up! Although I still don't understand why the service worker was fine for a different hostname with the same code, but after disabling it sessions work fine now! Will leave this here in case anyone else stumbles upon session issues and don't immediately think about any service workers they have.
Since migrating to Laravel 5.2 I've been having session persistence problem with Session::flash and subsequent Session::keep usage.
I know I'm supposed to use the web middleware group, and I am. But that isn't solving my problem. Please see below:
app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
...
\Illuminate\Session\Middleware\StartSession::class,
]
];
app/Http/routes.php
Route::get('test', function(Request $request) {
$request->session()->flash('test_flash', "Some value");
return redirect('/flashed');
});
Route::get('flashed', function(Request $request) {
$request->session()->reflash();
return redirect('/flash-kept');
});
Route::get('flash-kept', function(Request $request) {
var_dump($request->session()->get('test_flash'));
});
The first time I hit /test it redirects to /flash-kept with value of test_flash as NULL - but second time I hit it, again it redirects but this time with correct value! And this is consistent in that every time I load any other page, then load /test it doesn't keep the flash message, only second time hitting it does.
Can someone see anything wrong??
This is happening on a Debian machine running PHP 5.6.30, very interestingly I cannot replicate this behaviour on my local machine, macOS running PHP 7.1 - but I don't think it's PHP version either as I quickly tried downgrading my local machine to use PHP 5.6 and I still couldn't re-create the issue! I've been staring at this for the last few hours, cannot see anything wrong!
Related
I've been laraveling for 5 months now but I reformatted ubuntu and installed Laravel, this time, it's Laravel 7 instead of Laravel 6. My problem is simple routing giving an error. It's so dead simple you might think I'm a stupid beginner.
In my Web.php
Route::get('/about', function () {
return view('welcome');
});
Route::get('/', function () {
return view('welcome');
});
I also tried using a controller that returns a view and just a simple "string" in Web.php
Route::get('/about', 'UserController#index');
Typing http://localhost/about in the address bar in chrome causes 404 error.
As you can see, there should be no problem returning the same view('welcome'), even if I return a simple return "TEST";, results are the same.
I tried downgrading to Laravel 6 by deleting vendor, changing the Laravel v6 in composer.json and running composer install but still the same, so I think it's not the version.
This has never happened to me before even when I first started with Laravel 6 five months ago and it's a totally fresh project.
enable rewrite_mode of Apache server and restart Apache server it will solve the issue.
Run server with php artisan serve
and then try http://localhost:8000/about hope it will fix your problem
OR
Simply use http://localhost/project/about
I have multiple Laravel sites hosted on the same server. With the latest site I've created, the contact form refuses to submit without throwing a 419 error. I have set up the routing in my web.php file just like the other websites, which have live, working contact forms, and I'm generating and sending the token exactly the same way - with {{ csrf_field() }}.
I found an answer to a similar question stating that you can disable Csrf checking by adding entries to the $except array in app/Http/Middleware/VerifyCsrfToken.php. I have verified that this does indeed resolve the 419 error:
protected $except = [
'contact',
'contact*',
];
But of course I wish to keep the Csrf functionality, and I only updated the $except array for troubleshooting value.
Does anyone know what may be different about the new Laravel environment that would have this 419 behavior despite passing the generated token? I have tried updating a number of ENV settings and toggling different things, but nothing other than modifying the $except array has had any influence on the issue.
Update
Since there has been a bit of discussion so far, I figured I'd provide some additional info and code.
First, this is an ajax form, but don't jump out of your seat just yet. I have been testing the form both with and without ajax. If I want to test with ajax, I just click the button that's hooked up to the jQuery listener. If not, I change or remove the button's ID, or run $("#formName").submit(); in the console window.
The above (ajax, old-fashioned submit, and the jquery selector with .submit();) all result in the exact same response - a 419 error.
And for the sake of completeness, here's my ajax code which is working on all of the other websites I'm hosting. I define a postData array to keep it all tidy, and I added a console.log() statement directly after it to (again) confirm that token is generated just fine and is being passed correctly with the request.
var postData = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#message").val(),
_token: $("input[name=_token]").val()
};
console.log(postData);
$.post("/contact", postData, function (data) {
...
Any ideas? Could there be a configuration issue with my ENV or another file?
Progress Update!
Because the other sites are working just fine, I cloned an old site and simply overwrote the files that I changed for the new website, and bam! It's working now. Doing a little bit more digging, I ran php artisan --version on the cloned version of the site versus the non-working version, and here are the results:
Working Version: Laravel Framework 5.7.3
Non-working Version: Laravel Framework 5.7.9
Perhaps this is a bug with Laravel? Or perhaps some packages on my server are out of date and need to be updated to work with the new version of Laravel?
TLDR: This post contains lots of potential issues and fixes; it is intended for those scouring for related bonus information when stuck.
I just encountered this error using Laravel Sanctum in what looks like improperly setup middleware. Sanctum uses the auth:sanctum middleware for the guard, which is some kind of extension of the auth guard of which Laravel uses as the default, but session is handled by the web middleware group.
I can't exactly verbalize some of this internal-Laravel stuff; I am more experienced with JavaScript than PHP at the moment.
In my api.php file, I had the login/register/logout routes, and in my Kernel.php file, I copied \Illuminate\Session\Middleware\StartSession::class, from the web group into the api group.
I had to do that to fix my login unit test that was throwing an error about "Session store not on request". Copying that allowed me my postJson request to work in the unit test, but sometime later, I started seeing 419 CSRF error posting from the JavaScript app (which is bad because it worked fine earlier).
I started chasing some filesystem permission red-herring in the /storage/framework/sessions folder, but the issue wasn't that (for me).
I later figured out that with Laravel Sanctum and the default AuthenticatesUsers trait, you must use the web guard for auth, and the auth:sanctum middleware for protected routes. I was trying to use the api guard for auth routes and that was central to my 419 errors with the AuthenticatesUsers trait.
If anyone gets 419 while CSRF was working or should work, I recommend doing some \Log::debug() investigations at all the key points in your system where you need these to work:
Auth::check()
Auth::user()
Auth::logout()
If you get strange behaviour with those, based on my observations, there is something wrong with your config related to sessions or something wrong with your config related to web, api guards.
The guards have bearing on the AuthManager guard which maintains state over multiple requests and over multiple unit tests.
This is the best description I found, which took over a week for me to discover:
Method Illuminate\Auth\RequestGuard::logout does not exist Laravel Passport
As a random final example, if your session is somehow generating the CSRF token using data from the web middleware group while your routes are set to use api, they may interpret the received CSRF incorrectly.
Besides that, open Chrome dev tools and goto the Applications tab, and look at the cookies. Make sure you have the XSRF-TOKEN cookie as unsecure (ie: not httpOnly).
That will allow you to have an Axios request interceptor such as this:
import Cookies from 'js-cookie';
axios.interceptors.request.use(async (request) => {
try {
const csrf = Cookies.get('XSRF-TOKEN');
request.withCredentials = true;
if (csrf) {
request.headers.common['XSRF-TOKEN'] = csrf;
}
return request;
} catch (err) {
throw new Error(`axios# Problem with request during pre-flight phase: ${err}.`);
}
});
That is how my current Laravel/Vue SPA is working successfully.
In the past, I also used this technique here:
app.blade.php (root layout file, document head)
<meta name="csrf-token" content="{{ csrf_token() }}">
bootstrap.js (or anywhere)
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
const token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
In my opinion, most problems will stem from an incorrect value in one or more of these files:
./.env
./config/auth.php
./config/session.php
Pay close attention to stuff like SESSION_DOMAIN, SESSION_LIFETIME, and SESSION_DRIVER, and like I said, filesystem permissions.
Check your nginx access.log and/or error.log file; they might contain a hint.
just found your issue on the framework repo.
It is not a laravel issue, your installation is missing write permissions on the storage folder, thus laravel can't write session, logs, etc.
You get a 419 error because you can't write to the files, thus you can't create a sessionn, thus you can't verify the csrf token.
Quick fix: chmod -R 777 storage
Right fix: move your installation to a folder where nginx/apache/your user can actually write.
If you are using nginx/apache, move you app there and give the right permissions on the project (chown -R www-data: /path-to-project)
If you are using php artisan serve, change it's permissions to your user: chown -R $(whoami) /path-to-project
You get it, let writers write and you're good.
Probably your domain in browser address bar does not match domain key in config/session.php config file or SESSION_DOMAIN in your env file.
I had the same issue, but the problem in my case was https. The form was on http page, but the action was on https. As a result, the session is different, which is causing the csrf error.
run this command
php artisan key:generate
I used the same app name for staging and prod, being staging a subdomain of prod. After changing name of app in staging it worked
We had this issue, it turned out that our sessions table wasn't correct for the version of Laravel we were using. I'd recommend looking to see if it's being populated or remaining empty (like ours was).
If it's empty, even when you have people visiting the site, I'd say that's what the issue is.
(If you're not using a database to store your sessions, obviously I'd suggest checking wherever you are instead.)
hope you're good
I was trying to add a profile table to my Laravel 5.6 project, and I'm also using the spatie\Laravel-Permission package. It was working fine, but after I ran some migrations (that have nothing to do with users), it started failing on the login. The curious thing is that, if I register a new user, it gets logged in properly, but never with the /login route (I'm using the Laravel's Auth scaffolding).
After debugging the project, I came up with the method that's failing, it's something reading the sessions:
MyProject\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php
<?php
namespace Illuminate\Filesystem;
use ErrorException;
use FilesystemIterator;
use Symfony\Component\Finder\Finder;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
class Filesystem{
// ...
public function get($path, $lock = false)
{
if ($this->isFile($path)) {
return $lock ? $this->sharedGet($path) : file_get_contents($path); // <-- The failing line
}
throw new FileNotFoundException("File does not exist at path {$path}");
}
// ...
}
Once it gets to that line, the debugger stops, the browser doesnt get a response, the dd() function does not get triggered... I also tried to debug the sharedGet($path) method, and it returns the value, but back to the method above, it stops.
Also, the php_error.log file gets absurdly increased on every request (up to 500MB/request), so much that none of the editors I use can open it (SublimeText, NetBeans).
My thoughts are that apache may be running out of memory when reading the files, but the session file barely weights 1k, so it wouldn't make much sense.
Can someone throw any clue? Thanks
--EDIT:
I tried installing a fresh laravel proyect with only the Auth module and the spatie/laravel-permission package, and I noticed the same behaviour: it registers and logs users, but after logging it out, I'm no longer able to log in with any user.
In case someonw gets to the same error:
I could manage to solve this by backing up all my projects/databases and reinstalling wampserver with the last version of php (by the moment of this answer, it is 7.2.4) and reinstalling Laravel (luckily the proyect was barely starting), which only updated vlucas/phpdotenv package from 2.4.0 to 2.5.0 and phpunittest.
Whith this update now I can log in users normally, now let's see if it works as it should with spatie/laravel-permission package and the profile table I need to add.
I'm new to Laravel, I have learned about the models, views, blade, controllers and routes and how they work together. So far everything has been working smoothly.
I'm having trouble with sessions though.
When I use the AuthController that comes with Laravel and hit auth/register with a POST request, the data for the user that I register does get inserted into the users table (using mysql) and I do get back a response with the "Location" header redirecting to / like it does out of the box. It redirects like it should. But in the same response there is no "Set-Cookie" header set/sent. The session part of Laravel is not working properly for me. This is the same for a POST to auth/login, it authenticates properly and redirects to the profile page but no session cookie is sent back in the response.
I'm using:
Laravel 5.2.11
PHP 5.5.9
xubuntu 14.04 (Ubuntu)
Linux kernel 3.19.0-42-generic
Composer 1.0
All of the php modules that Laravel requires are installed. I'm running the app with php's built in web server. I run that with sudo. The exact command I run is this:
sudo php -S localhost:8888 -t public/
All routes are being responded to properly.
I have tried both ways of installing Laravel that the installation docs recommend, through the laravel executable and composer create-project. Still no cookies set either way. I have made all the files and directories of the laravel project mod 777. The app key is set in .env if that makes any difference.
The config/session.php file is using the file driver for the session.
There are no session files in the storage/framework/sessions directory after setting a session.
When I try setting a session myself with the session function like it states in the docs:
session(['sesskey' => 'somevalue']);
Again no "Set-Cookie" header is sent in the response and no session file is created. There are no error messages reported back either I should add.
When I do set a session key with the session function like above I can get that value back however and echo it back to the browser like so:
echo session('sesskey');
So it does seem to save it at least in php's memory.
When I try setting a cookie using the withCookie method, I do get the proper response with the Set-Cookie header set:
return response()->view('welcome')->withCookie(cookie("test", "val" , 3600));
I tried going down the illuminate rabbit hole to see if I could find a problem but that is a bit over my head atm.
Any help would be much appriciated, thanks!
in laravel 5.2 you need to use "web" middleware for your problem,like that
Route::group(['middleware' => ['web']], function () {
//
});
use middleware for the request \Illuminate\Session\Middleware\StartSession::class
Route::group(['middleware' => [\Illuminate\Session\Middleware\StartSession::class]], function () {
});
I have a Magento 1.6.2 site hosted on 1&1. Because of certain installed extensions I must have support for PHP version 5.3, but sadly the available options with 1&1 are PHP 5.2 or something they call PHP Dev. A quick phpinfo() shows that this is in fact PHP 5.4.
My problem is that when I'm set to 5.4, the Categories page of the backend throws a 500 error. Rolling back to 5.2 fixes the issue, but that breaks my product pages. In the short term I can handle having to swap between them, but this is obviously unacceptable for a long-term solution when the site is handed to the client.
Can anyone suggest where this incompatibility might lie, and what steps I might take to fix it? My biggest impediment is that the hosting is on a shared server, and so I am not allowed to look at the Apache logs.
Update:
As per CCBlackburn's suggestion in the comments, I have tried to track the point that the error originates from, but I have to admit that I don't really understand the results I'm getting. The URL of the categories page looks like this:
example.com/index.php/admin/catalog_category/index/key/blahblah
I presumed that Mage_Adminhtml_CatalogController would be the place to start looking, but a Mage::log() call as the first line in indexAction() failed to write to the log.
I decided to move up the inheritance and cut into the constructor, and so added the following to Mage_Adminhtml_Controller_Action:
function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) {
Mage::log('construct pre');
parent::__construct($request,$response,$invokeArgs);
Mage::log('construct post');
}
This was better, as the first log call wrote to the file, but the second did not.
Next I moved up the inheritance again, and modified the constructor of Mage_Core_Controller_Varien_Action as follows:
public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array())
{
Mage::log('request: '.$request);
$this->_request = $request;
Mage::log('response: '.$response);
$this->_response= $response;
Mage::log('pre set action');
Mage::app()->getFrontController()->setAction($this);
Mage::log('post set action');
$this->_construct();
}
The problem is that none of these log calls do anything. This has me stumped, as surely calling parent::__construct(); from Mage_Adminhtml_Controller_Action should execute at least one more log call before it does anything. Unless the issue exists with the incoming values, but I don't know how I can check/debug that?
I have faced the same problem under OSX Lion in Google Chrome and Apple Safari with Magento 1.7 and PHP 5.4. Suddenly Magento Category admin started giving 500 Errors and I had no clue what was happening. It seems it's a problem with PHP 5.4. At first I thought it was XDebug causing this error. Then I disabled XDebug and the problem was still there. It is weirder than weird that it works with Firefox!
My solution was to downgrade to the latest PHP 5.3, however this has now been fixed as of PHP 5.4.3.