I need to show some values in all app, and sometimes I need to use these values between controllers.
I was trying to use Session, but I maybe it is not the answer to that, because if I am not wrong, Laravel store the session data temporarily in memory and only after everything has been executed, will it dump the session data into storage (file, cookie, redis, whatever).
So for example, I have a controller like that:
class GiftController extends Controller
{
public function dashboard(){
$token = (Session::has('token')) ? Session::get('token') : NULL;
if (is_null($token)){
return view('test.erro', ['message' => 'no session!']);
}else{
return view('test.ok', ['message' => $token]);
}
}
public function setsession(){
Session::put('token','xxxxxxxxxxxx');
return redirect('test/dashboard');
}
}
In this case, if I do an echo on Session::get('token') into the setsession(), is showing the value, but when it goes to the dashboard(), the session shows nothing.
What I am doing wrong?
or What is the better Idea to use instead off session?
I am using the Laravel Framework 5.8.37
I found the solution but I got it with the markskayff help.
He told me to Check my .env file, and he was right! It was a different SESSION_DRIVER value from config/session.php
In config/session.php was 'driver' => env ('SESSION_DRIVER', 'file')
Despite not having .env file but app.yaml since I am doing this project in GCP app engine, the session in this file was SESSION_DRIVER: cookie.
So I changed in config / session.php the line 'driver' => env ('SESSION_DRIVER', 'file') to 'driver' => env ('SESSION_DRIVER', 'cookie').
And now it is working!
Related
I have a project on Laravel 5.4 and PostgreSQL. At each page request, the session is renewed with a new _token key and a new cookie. As a consequence, either authentication nor flash sessions message are not working.
Already tried :
Changed laravels' cookie name
Played with $domain variable in session.php, tried null, http://localhost:8000 and http://localhost
Switched from file to array and redis
Played with encrypted => false/true and all others booleans fields
Checking storage/sessions folder permissions (all set to 777)
In my routes.php file, replaced middleware by middlewareGroups
The RouteServiceProvider.php :
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
(there is no web.php/api.php, etc... PHP files, the developper remapped all these files into routes.php).
Your domain is invalid. You need to look at config.session.domain and config.session.path.
Your browser will not store cookies for a domain without a dot. E.g. localhost. A simple fix is to add 'localhost.com' to your hosts file as 127.0.0.1.
Then you can use for example: localhost.com:8080
I'm using sessions for the first time in Laravel and I'm trying to do a multiple step form, so I thought using sessions would be a smart move. however the following code returns a null value, what am I doing wrong?
$user_information = [
"name" => $request->name,
"email" => $request->email,
"remember_token" => $request->_token,
"password" => bcrypt($request->password),
"role_id" => 3
];
session('user_signup', $user_information);
dd(session('user_signup'));
In your controller you can save variable into session like
session()->put('user_signup',$user_information);
For checking your session variable in controller
session()->has('user_signup','default value');
For deleting your session variable in controller
session()->forget('user_signup');
For checking your session variable if it exists in blade and printing it out
#if(session()->has('user_signup'))
session()->get('user_signup')
#endif
I have tested this already and struggling along then I realized that I should never use dd() (the dump and die method) after using the session() because your are blocking the system from writing on the session() cookie file.
I'm not really sure about that but it works for me .. let me know if this is True.
Try this
session(['user_signup'=> $user_information]);
or
session()->put('user_signup',$user_information);
and you can check session by logging it
Log::info(Session::get('user_signup'));
check your log file it should be there.
Laravel docs link - https://laravel.com/docs/5.4/session#storing-data
first : you put something in a session
second : check the storage/framework/session folder , if your session work fine you can see your session data in a session folder now.
if you save a session and session folder is still empty :
first change the 'driver' => env('SESSION_DRIVER', 'file')
to 'driver' => env('SESSION_DRIVER', 'array') and 'driver' => env('SESSION_DRIVER', 'database')
second set the storage/framework/session permission to 755
and finally go to your kernel file and add bellow code in 'api'
'api' => [
//add this bellow two line
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
'throttle:60,1',
'bindings',
],
then check your session folder again and if you put something in any session you should now see them in this folder, you can delete files in session folder, use the session again to save something in it , going back to session folder and see the session folder is not empty anymore , and you're done, image of the session folder
As the title reads, I can't get my session variables to be persistent over routes.
I call session_start() at the VERY beginning of my index.php.
Root route:
$app->get('/', function (Request $request, Response $response) {
$this->logger->addInfo("session id: " . $_SESSION['cus_id']);
$response = $this->view->render($response, "homepage.phtml", [
'test' => 'testing something',
'logged_in' => isset($_SESSION['cus_id'])
]);
return $response;
});
in my app.log I see that the session variable is non existent.
But this is my code after a successful login: (post to /login)
if ($customer !== false && password_verify($password, $customer['password'])) {
$_SESSION['cus_id'] = $customer['id'];
return $this->view->render($response, "homepage.phtml", [ 'logged_in' => true]);
}
I also used the logger here for testing purposes and it showed me that it saved the right id.
I have also used various extra libraries with the exact same result.
I also checked the official documentation, to no avail.
Question:
How do I get the session variables to be persistent throughout routes?
Or is the another way to save sessions? and or another way to solve this login problem?
I had the same problem after upgrading a server which resulted in a new server setting in the php.ini file.
For me, session.auto_start=1 in the php.ini did the trick.
Here's config/session.php:
return [
'driver' => 'file',
'files' => storage_path().'/framework/sessions',
];
My storage/framework/sessions have 755 permissions.
When I put these 2 line in my controller
Session::set('aa', 'bb');
dd(Session::get('aa'));
I receive expected "bb" output. But if I comment first line:
// Session::set('aa', 'bb');
dd(Session::get('aa'));
and refresh page, I still expecting "bb" but getting null.
Also, storage/framework/sessions is empty.
What should I do to make Session working?
Laravel 5 handles sessions via a middleware class called StartSession. More importantly, this middleware is a TerminableMiddleware and the code that actually saves the data (in your case to the session file) is located in the terminate method, which is run at the end of the request lifecycle:
public function terminate($request, $response)
{
if ($this->sessionHandled && $this->sessionConfigured() && ! $this->usingCookieSessions())
{
$this->manager->driver()->save();
}
}
When calling dd(Session::get('aa')); the request is being interrupted before the terminate method of the middleware can be called.
Funnily enough, the Laravel Middleware Documentation actually explains Terminable Middleware logic by giving the Laravel StartSession middleware as an example:
For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser.
That being said, try using var_dump() instead of using dd().
With laravel 5.*, you must change the kernel file like bellow:
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
'throttle:60,1',
'bindings',
],
then go to storage/framework/session folder and change the permission to 755 if it has another amount, then delete all files in your storage/framework/session path, use your code again to put something in a session, watch the storage/framework/session folder.
If your session work you can see the weird long file that belong to session right now, and you are done!
If your problem is not yet solved, go to config/session and change:
'driver' => env('SESSION_DRIVER', 'file')
to another predefined amount like:
'driver' => env('SESSION_DRIVER', 'array'),
or even
'driver' => env('SESSION_DRIVER', 'database'),
and finally if you have an empty folder of storage/framework/session, you still have a problem for sure !!!
if you're use api route , you might have this problem with your session and most of the time sessions return null ,
try to use web route for this
I am working on an application based on laravel. I need to set my database password in the config so that laravel can use it to connect to the database.
Now I have two problems:
1) I don't want to set password for every other local environment I use.
2) I don't want to set the password in the config file because when I share the code with my team members on git, they can view my password.
I may have figured out a way around this which is to store the password in an environment variable and then use the getenv() PHP function to retrieve it in the config file. So now I can just set the environment variable in any number of environments and the code in the config file will remain the same, and also the other members won't be able to see my password.
Now I don't know how to set environment variables, and other stuff like global/local environment variables and temporary/persistent variables.
And if I am storing the password in the environment variables, should I hash these passwords? Will they be accessible to other users who log onto my machine?
And if I do hash them and store them, how am i supposed to use them in the config file?
Is there a different, a more ideal way around my problem?
Laravel Way
Laravel uses .env.php files to solve this for you: http://laravel.com/docs/configuration#protecting-sensitive-configuration. But as you still need to set the environment in your start.php file, I prefer to do it differenlty:
My Way
I create a .environment file in my app root folder with things like:
<?php
return [
'LARAVEL_ENV' => 'development',
'DOMAIN' => 'myapp.com',
'DEBUG_MODE' => true,
'MAIN.DATABASE_HOST' => 'localhost',
'MAIN.DATABASE_NAME' => 'databasename',
'MAIN.DATABASE_USER' => 'myusername',
'MAIN.DATABASE_PASSWORD' => 'basswort',
];
I have a class to load the environment file:
<?php
namespace PragmaRX\Support;
use Exception;
class Environment {
protected static $loaded = false;
public static function load($file = null)
{
if ( ! static::$loaded)
{
if ( ! file_exists($file))
{
throw new Exception('Environment file (.environment) was not set or does not exists: '.$file);
}
foreach(require $file as $key => $value)
{
if ($value === false)
{
$value = '(false)';
}
else
if ($value === null)
{
$value = '(null)';
}
else
if (empty($value))
{
$value = '(empty)';
}
putenv(sprintf('%s=%s', $key, $value));
}
static::$loaded = true;
}
}
public static function getDetectionClosure($file = null)
{
static::load($file);
return function() { return getenv('LARAVEL_ENV'); };
}
}
Then in my app/bootstrap/start.php I just need to load it this way:
$env = $app->detectEnvironment(
\App\Environment::getDetectionClosure(__DIR__.'/../.environment')
);
As you can see, the closure will return the current LARAVEL_ENV, stored in my .environment file. But it also will load all keys to the PHP environment, so, now, in my application I just need to
<?php
return [
'fetch' => PDO::FETCH_CLASS,
'default' => 'main',
'connections' => [
'main' => [
'driver' => 'pgsql',
'host' => getenv('MAIN.DATABASE_HOST'),
'database' => getenv('MAIN.DATABASE_NAME'),
'username' => getenv('MAIN.DATABASE_USER'),
'password' => getenv('MAIN.DATABASE_PASSWORD'),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
],
],
];
Add the .environment file to your gitignore file and you should be safe, but you'll have to, of course, create (or copy and edit) the file every time you set a new server.
About Security
Everything in your system is a file, you are protected if your files are protected. It's that simple. A VirtualHost file is a file accessible by your webserver, if someone hacks your webserver you'll have not only your .environment file exposed, but also your VirtualHost one, so IMO you're not securer using one or another.
I'm not an expert on security by any means but I think you should avoid trying to do what you want to do and just define your environments. If you really want to set an environmental variable this is how you do it in Ubuntu:
In your vhost:
<VirtualHost *:80>
SetEnv APP_ENV "test"
...
</VirtualHost>
I assume Windows is your client machine?
There are many good answers already, but as a side note. You can include your DB config file in .gitignore so it won't be shared among the development team by git. Something like config.php.orig in the project files and your own copy config.php listed in .gitignore should do the trick.