I'm trying to get sessions to work in Laravel 5.7, but I can't seem to get it working; I'm not sure why. I've looked at the official docs, looked at a bunch of SO posts, done Googling for the issue on other sites, and I still can't figure it out.
Basically, I've got a route like the following in web.php:
Route::get('/some_path', 'SomeController#index');
Then, in the index method of SomeController, I have the following:
session(['test', 'Some Value']);
session(['test2', 'Some Other Value']);
session(['test3', 'Some Third Value']);
$value = session('test', 'Backup Value');
echo $value;
With that, I'm always getting Backup Value echoed to the screen.
If I go into /storage/framework/sessions, I see a session file that has the following content (which I have anonymized):
a:5:{s:6:"_token";s:40:"token-here";s:9:"_previous";a:1:{s:3:"url";s:26:"http://example.com/some_path";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}i:0;s:5:"test3";i:1;s:16:"Some Third Value";}
Basically, it looks like the session is kind of working, but it only seems to store test3. If I comment out the test3 line in the controller, then it only stores test2. And even if I only have the test line in the controller, it still doesn't retrieve the value.
I also tried switching the session to a DB session with the proper session migrate file a la https://laravel.com/docs/5.7/session, but it's still not working.
Basically, I have no clue what's up. I can say that I'm not using the native Laravel auth, so I'm not sure if that matters, but I feel like it shouldn't. Also, I tried restarting my localhost, but that didn't make a difference and running both of the following commands, neither of which seem to change anything:
php artisan config:clear
php artisan route:clear
Lastly, I tried adding use Session at the top of the controller, but that doesn't seem to matter either.
Basically, I don't know what to do. What could possibly be causing this? Thank you.
What's happening here is that when you add this:
session(['test', 'x'])
It adds test at the 0th index of the session and x at 1st.
Now when you again do a session(['test1', 'xx'])
It overwrites the 0th and 1st index of session with new values.
Therefore when you print the session data you get the last values.
You can check this by doing a dd(session()->all()) and seeing the same on screen.
If you want to make a key value relation and store the data in such away, please use the syntax like this:
session(['test' => 'x']);
session(['test1' => 'xx']);
those who are unable to save the session the issue is you guys are forgot to put the save() function after put given is the example.
$cartCount = Session::get('cartCount');
if(empty($cartCount)){
$cartCount = 0;
Session::put('cartCount', $cartCount);
}
Session::save();
Session::save() can be a life saver, definitely try that if still issues.
Laravel 5.7 - store value in session with File system:
Set the value in session:
session()->put('email', 'jai#gmail.com');
Get the value from session:
$email = session()->get('email');
Delete the session of email:
session()->forget('email');
It works like charm :)
If for some reason your code doesn't run through - eg you're using dd() somewhere, then your session will never save. This tripped me up for a good 20 minutes.
In this case, all you need to do is add a "web" middleware chain function to your route rule.
e.g
Route::get('/some_path', 'SomeController#index')->middleware('web');
Then clear cache:
php artisan config:clear
php artisan route:clear
Related
I have a very special problem and I don't know how to deal with it.
I have web App in Laravel, when i open index page, I receive text message to my mobile phone.
Problem is, sometimes I receive 2 messages or 3, sometimes 1.
Is there a tool how to debug this strange behavior which is not always the same?
A few words about my code:
user opens the page, and because its first visit Session doesn't have attribute message_sent and SendTextMessage::SendMessage($phoneNumber, $id_message, $smsCode, $newDateFormat); is executed. After that Session has message_sent and can't be sent again, for example if I refresh the page.
SendTextMessage::SendMessage() is Class in Laravel Helpers.
controller code:
public function index($url_attribute, $id_message, Request $request)
{
if(!Session::has('message_sent'))
{
$user = User::where('id_message', $id_message)->first()->toArray();
$phoneNumber = $user['mobile_phone'];
$smsCode = $user['sms_code'];
$newDateFormat = date("d.m.yy", strtotime($smsExpirationTime));
$request->session()->flash('message', 'Text message sended.' );
SendTextMessage::SendMessage($phoneNumber,$id_message, $smsCode, $newDateFormat);
Session::put('message_sent', true);
}
return view('login');
}
SendTextMessage Class:
class SendTextMessage
{
public static function SendMessage($phoneNumber, $id_message, $smsCode, $newDateFormat)
{
$sms = new Connect();
$sms->Create("user","pass",Connect::AUTH_PLAIN);
$sms->Send_SMS($phoneNumber,"Message");
$sms->Logout();
}
}
Many thanks for any tip or help.
UPDATE:
problem is only in Chrome.
Edge and internet explorer are fine.
As this script runs on server-side the browser shouldn't be an issue. Based on your code provided, there is no clear answer to give here.
Please try the following in order to debug your problem:
Log messages at each stage of the script in order to see which part was called how often. That will help you to locate the problem. You can use \Log::error("Message") to do that.
Once you know where the problem might be, try to log "decision" making / mission critical variables to logile as well. E.g. \Log::error($session) so that you can understand why that problem might occur. One reason could be that you have a bad configured session caching or your cookies might be messed up. At some point there is probably a piece of data not the way you expect it to be.
You should maybe try to change the way you use Laravel Session.
You indicated that it was working fine on some browsers, that means your server-side code is correct so far, but there is someting messing with Chrome… From there,
if you take a quick look at the Laravel Session doc, you'll see that Session can be stored in cookies, and I bet that this is your actual setup (check in your .env file the SESSION_DRIVER constant, or in your config/session.php file).
If so, to confirm that this cookies-based session setting is the culprit, you might want to change the Session config to make it browser-independent: any other option than cookies will work, the database or file options might be the easier to setup… And if it works I would strongly encourage you to keep using this no-cookie setting to make your code browser-safe.
Good day,
I have been struggling with this for the past few hours but admittedly I'm not very familiar with Laravel.
I use this row of code to generate a cookie:
return Response::make(view("/play"))->withCookie(cookie('username', $request->input('username'), 60000));
I have logged $request->input('username') and it is not empty,
the application goes to the /play view but when I use Cookie::get('username')in a later method in another Controller later on it returns null.
picture of cookie storage it also does not appear empty in the browser.
Does anyone know why this is happening and how to fix it?
try Request()->cookie('username')
Background:
I tried to write a setup wizard using Laravel 5.5. Some database parameters (database name, user, password) should be written to .env file and then validated. The writing process could be done with this.
Problems I met:
After wrote posted variables into .env file successfully, I tried to reload the variables using code like env('DB_DATABASE'). I found the variables remain unchanged. But after I refreshed the page, the variable will change to correct one. I did check the variables in .env file were already updated before I refresh the page.
What I have tried:
I tried to find a solution. Most solutions refer to use artisan config:clear command. So I put artisan command to my controller like this:
$this->changeEnvironmentVariable('DB_DATABASE',$request->input('db_name'));
$this->changeEnvironmentVariable('DB_USERNAME',$request->input('db_user'));
$this->changeEnvironmentVariable('DB_PASSWORD',$request->input('db_password'));
Artisan::call('config:clear');
But it doesn't work although there are no warnings and errors. The env('DB_DATABASE') still keeps the previous value.
Question:
I could work around this by validating the database information using the posted information instead of load the variables from .env file. However, I just want to know whether there is a way to write and reload .env variables in real-time.
Any comments are appreciated.
I created a readEnv and changeEnv method to read and write .env file without using env() directly . Which could avoid using the cached data. Hope it could help people who may have similar needs like me.
public function readEnv(){
$root_dir = realpath(dirname(getcwd()));
$ini_array = parse_ini_file($root_dir.'\.env', true, INI_SCANNER_RAW);
$this->env_str[0] = $ini_array['DB_DATABASE'];
$this->env_str[1] = $ini_array['DB_USERNAME'];
$this->env_str[2] = $ini_array['DB_PASSWORD'];
return;
}
public static function changeEnv($key,$value)
{
$path = base_path('.env');
if(is_bool(env($key)))
{
$old = env($key)? 'true' : 'false';
}
elseif(env($key)===null){
$old = 'null';
}
else{
$old = env($key);
}
if (file_exists($path)) {
file_put_contents($path, str_replace(
"$key=".$old, "$key=".$value, file_get_contents($path)
));
}
}
Your environment write can be successful but without page reloading or go another link this env value will not change. If need to apply this value in current controller or link you can use following lines.
putenv('DB_DATABASE='.$request->input('db_name'));
putenv('DB_USERNAME='.$request->input('db_user'));
putenv('DB_PASSWORD='.$request->input('db_password'));
Now env('DB_DATABASE') will show output of your input value.
I have an issue with post variables in Codeigniter, for now I fixed it, but I'm not sure if this is fine, in other words, I'd really like to know why I had issue only on hosting server, not on local.
The problem:
I wanted more secure script so I replaced $_POST/$_GET with $this->input->post and $this->input->get, like in this example:
if(!empty($this->input->get('endDate'))){
$data['datepicker'] = $this->input->get('thisDate');
}
this was all working fine on my localhost, but I assume it is wrong way, as when I deployed to the hosting server, I've got ajax parse error from validation engine that I'm using, I couldn't log in the system, getting all the time ajax parse error, and somehow figured out that whenever I checked if empty$this->input->post('var) or the same with get, was wrong.
I have checked the input class from Codeigniter and figured out, that $this->input->post is returning true/false, so I changed the scripts in the format like this:
if(!($this->input->get('endDate'))){
$data['datepicker'] = $this->input->get('thisDate');
}
this worked fine.
I'm still wondering - why the code worked on the localhost, but it didn't on the server or what is the best way to check if the POST/GET variable is empty or not.Seems I really miss something out.
Thank you.
Consider that checking for empty($this->post->get('var')) will always return false, no matter if the POST/GET exists, so it might be for that reason only. - So i'm not sure why you got the error on a different environment, but the first statement is wrong, it's exactly like writing if(true)
Also, I'd check for a strong assertion of false for inputs, You never know when you might need a zero as an input and if you're used to this practice, you might get an accidental false.
I'm building a simple app and trying to test DB result output. But unfortunately all I'm getting is an array of size 0. Here's the controller code excerpt:
$data['query'] = $this->db->query('SELECT role_id, role_privilege FROM role');
$this->load->view('welcome_message', $data);
And a view code excerpt:
<?php
echo count($query->result_array())."<br/>";
foreach ($query->result() as $row){
echo $row->role_id . '<br/>';
echo $row->role_privilege . '<br/>';
}
echo 'Total result '.$query->num_rows();
?>
And what I get is next:
0
Total result
Running query from a command line gives a 2 rowed output. Can someone point out what i'm missing?
EDITED:
This issue is also discussed here .
EDITED:
Maybe some platform specific stuff (I really doubt that)? I'm running LAMP (php 5.3.2, mysql 5.1.37, apache 2.2.15).
EDITED:
This prints out a "Array ( )" string. My DB is 100% filled. I can say that for sure, because I did
INSERT INTO role(role_privilege) VALUES ('ROLE_MODERATOR');
INSERT INTO role(role_privilege) VALUES ('ROLE_USER');
and then checked it through a command line.
EDITED:
After I put this into my controller:
echo $this->db->last_query(); exit;
I get next output:
SELECT role_id, role_privilege FROM role
And that's exact sql query that I needed. Unfortunately results are o sized array.
Well, this here problem is basically not a CI related one, but strange thing is that CI couldn't track this error. Here's what was going on:
While installing php I haven't specified --with-mysql-socket parameter and it looks like php tried to use a /tmp/mysql.sock (default one) which obviously was not specified in my.cnf. So CI tried to bind to a nonexistent socket. Changing mysql params in a php.ini solved the problem.
Well, it sounds like your db access is set up properly because you're not getting an error. Which I think also means that the table exists. I know you said you ran that query from the command line, but are you certain you're accessing the same data set/server/table? No weird versioning or anything? It sounds like there aren't records in the role table. Sorry, just grasping at straws as your code looks right.
How about doing
SELECT * FROM role
and then doing a
print_r($query->result_array());
in your view? That should reveal column names at least so you know you're accessing the right data.
Try that and report back with any detail and hopefully it will supply some hints.